def getDialog(self): options = self.Parent._options return MDD.MultiDirDialog(self, message=options.get('message', _('choose_folders')), title=_('choose_folders_title'), defaultPath=options.get('default_path', os.getcwd()), agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST)
def test_lib_agw_multidirdialogCtor(self): dlg = MDD.MultiDirDialog(self.frame, title="Custom MultiDirDialog", agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST) wx.CallLater(250, dlg.EndModal, wx.ID_OK) dlg.ShowModal() dlg.Destroy()
def test_lib_agw_multidirdialogMethods(self): dlg = MDD.MultiDirDialog(self.frame, title="Custom MultiDirDialog", agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST) self.assertTrue(isinstance(dlg.GetPaths(), list)) # it looks like the generic dir ctrl may start out with an item # selected, so allow for that here self.assertTrue(len(dlg.GetPaths()) in [0,1])
def open_multiple_dir_dialog(message, default): dlg = MDD.MultiDirDialog(None, message=message, defaultPath=default, agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST) dirs = None if dlg.ShowModal() == wx.ID_OK: dirs = ud.smartdecode(dlg.GetPaths()) dlg.Destroy() return dirs
def onSelectDirs(self, event): dlg = MDD.MultiDirDialog(self, title="Choose source folder", defaultPath=self.currentDirectory, agwStyle=0) if dlg.ShowModal() == wx.ID_OK: paths = dlg.GetPaths() print "Source folder selected:" for path in paths: print path dlg.Destroy()
def onMultiDir(self, event): """ Create and show the MultiDirDialog """ dlg = MDD.MultiDirDialog(self, title="Choose a directory:", defaultPath=self.currentDirectory, agwStyle=0) if dlg.ShowModal() == wx.ID_OK: paths = dlg.GetPaths() print("You chose the following file(s):") for path in paths: print(path) dlg.Destroy()
def selectFolders(self): """ Select folders Args: None Returns: None """ if DEBUG: print("ImgProcsFrame.selectFolders()") dlg = MDD.MultiDirDialog( None, title="Select folders with images to process.", defaultPath=CWD, agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST, ) # select multiple folders if dlg.ShowModal() == wx.ID_OK: self.selectedFolders = dlg.GetPaths() if sys.platform == 'darwin': # OS X ### remove root string for i, fp in enumerate(self.selectedFolders): si = fp.find("/") if si != -1: fp = fp[fp.index("/"):] # cut off the fisrt directory name, # MultiDirDialog returns with disk name as root # Instead of '/tmp', # it returns 'Macintosh HD/tmp'. self.selectedFolders[i] = fp ### include sub folder, ### if "including sub folder" option was checked. sfChk = wx.FindWindowByName("subFolders_chk", self.panel["ui"]) if sfChk.GetValue() == True: ### update folder lists folderL = copy(self.selectedFolders) self.selectedFolders = [] for dp in folderL: # go through selected folders self.selectedFolders.append(dp) # append the selected folder self.addFolders(dp) # add sub-folders in this folder ### show folder list in UI selDir_txt = wx.FindWindowByName("selDir_txt", self.panel["ui"]) _txt = str(self.selectedFolders) _txt = _txt.strip("[]").replace("'","").replace(", ","\n\n") selDir_txt.SetValue(_txt) # show list of selected folders self.updateFileList() # update files to be renamed dlg.Destroy()
def select_save_dir(self, e): """ Opens quick dialog to select the save directory for the output files (.txt, .png) from the automatic measurements. Writes the directory name on the TextCtrl object on the GUI (self.save_tctrl). :param e: Event handler. :return: Nothing. """ # TODO: Currently, there is a problem with wx.DirDialog, so I have resorted to using multidirdialog # TODO: When the bugs are fixed on their end, revert back to the nicer looking wx.DirDialog with mdd.MultiDirDialog(None, "Select save directory for output files.", style=mdd.DD_DIR_MUST_EXIST | mdd.DD_NEW_DIR_BUTTON) as dlg: if dlg.ShowModal() == wx.ID_CANCEL: return # Correcting name format to fit future save functions path = dlg.GetPaths()[0] path = path.split(':')[0][-1] + ':' + path.split(':)')[1] self.save_tctrl.SetValue(path)
def select_multi_directory_dialog(): """ Opens a directory selection dialog Style - specifies style of dialog (read wx documentation for information) """ import wx.lib.agw.multidirdialog as MDD app = wx.App(0) dlg = MDD.MultiDirDialog(None, title="Select directories", defaultPath=os.getcwd(), agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST) if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() return paths = dlg.GetPaths() dlg.Destroy() app.MainLoop() return paths
def addDirectories(self): app = wx.App(0) dlg = MDD.MultiDirDialog(None, title="Custom MultiDirDialog", defaultPath="/home/lucas/Documents/Manip/", # defaultPath="C:/Users/users/Desktop/", agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST) if dlg.ShowModal() != wx.ID_OK: print("You Cancelled The Dialog!") dlg.Destroy() paths = dlg.GetPaths() dlg.Destroy() app.MainLoop() for path in enumerate(paths): directory= path[1].replace('Home directory','/home/lucas') filesToAdd = os.listdir(directory) for l in filesToAdd: l = directory + '/' + l self.textZone.insert(END, l+'\n') self.heightTextZone +=1 if self.heightTextZone >= 40: self.heightTextZone = 40 self.textZone.config(height=self.heightTextZone) if directory: self.buttonProcess.config(state=NORMAL)
def open_multiple_dir_dialog(message, default): if default is None: global default_dir default = default_dir dlg = MDD.MultiDirDialog(None, message=message, defaultPath=default, agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST) #dlg = wx.DirDialog(None, message, default, wx.DD_MULTIPLE) dirs = None if dlg.ShowModal() == wx.ID_OK: dirs = ud.smartdecode(dlg.GetPaths()) dirs2 = [] for d in dirs: p = Path(d) drive = p.parts[0] if ")" in drive: spot = drive.find(":") drive_letter = drive[spot-1] d=drive_letter+":\\" d2 = os.path.join(*p.parts[1:]) d = os.path.join(d, d2) dirs2.append(d) dirs = dirs2 dlg.Destroy() return dirs
def onButtonPressDown(self, event, flag=''): """ wx.Butotn was pressed. Args: event (wx.Event) flag (str, optional): Specifying intended operation of the function call. Returns: None """ if DEBUG: print("FileRenamerFrame.onButtonPressDown()") objName = '' if flag == '': obj = event.GetEventObject() objName = obj.GetName() if flag == "selectFolders" or objName == "selFolders_btn": # select folders to rename dlg = MDD.MultiDirDialog( None, title="Select folders to apply renaming operations.", defaultPath=CWD, agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST, ) # select multiple folders if dlg.ShowModal() == wx.ID_OK: self.selectedFolders = dlg.GetPaths() if sys.platform == 'darwin': # OS X ### remove root string for i, fp in enumerate(self.selectedFolders): si = fp.find("/") if si != -1: fp = fp[fp.index("/"):] # cut off the fisrt directory name, # MultiDirDialog returns with disk name as root # Instead of '/tmp', # it returns 'Macintosh HD/tmp'. self.selectedFolders[i] = fp ### include sub folder, if "including sub folder" option was checked. sfChk = wx.FindWindowByName("subFolders_chk", self.panel["tUI"]) if sfChk.GetValue() == True: ### update folder lists folderL = copy(self.selectedFolders) self.selectedFolders = [] for dp in folderL: # go through selected folders self.selectedFolders.append(dp) # append the selected folder self.addFolders(dp) # add sub-folders in this folder ### show folder list in UI selDir_txt = wx.FindWindowByName("selDir_txt", self.panel["mp"]) _txt = str(self.selectedFolders) _txt = _txt.strip("[]").replace("'","").replace(", ","\n\n") selDir_txt.SetValue(_txt) # show list of selected folders self.updateFileList() # update files to be renamed dlg.Destroy() elif objName == "selFolder2move_btn": # select folder to move renamed files dlg = wx.DirDialog(self, "Select a folder to move renamed files.", CWD) # select folder if dlg.ShowModal() == wx.ID_OK: self.folder2moveRenFile = dlg.GetPath() # get folder path tc = wx.FindWindowByName("selFolder2move_txt", self.panel["tUI"]) tc.SetValue(self.folder2moveRenFile) # show it on UI self.updateFileList() # update files to be renamed dlg.Destroy() elif objName == "run_btn": msg = "Renamed files -----\n\n" # result message msg4log = "" # log message for i, fp in enumerate(self.fileList): newFP = self.nFileList[i] rename(fp, newFP) # rename file msg4log += "%s, %s, %s\n\n"%(get_time_stamp(), fp, newFP) msg += "%s\n\n"%(newFP) writeFile(self.logFile, msg4log) # logging results self.initList() # clear all file lists wx.MessageBox(msg, 'Results', wx.OK)
def onAddDirectory(self, event): from obspy.core.util.base import ENTRY_POINTS from pkg_resources import load_entry_point import wx.lib.agw.multidirdialog as mdd # dlg = wx.DirDialog(self, "Choose a directory:", # style=wx.DD_DEFAULT_STYLE # | wx.DD_DIR_MUST_EXIST # ) waveclient = self.psyProject.waveclient['db client'] if waveclient.waveformDirList: start_path = waveclient.waveformDirList[0][2] else: start_path = os.getcwd() dlg = mdd.MultiDirDialog(self, title = 'Choose one or more directories', defaultPath = start_path, agwStyle = mdd.DD_DIR_MUST_EXIST) # BUGFIX FS#81 # When the DD_MULTIPLE style is used, the root folder is kept in the # selected paths list after setting the default path. When the user # doesn't select any folder, the root folder will be returned together # with the default path by the GetPaths() method. # Setting the MULTIPLE flag after the initialization as a single # selection dialog fixes this problem. dlg.dirCtrl.GetTreeCtrl().SetWindowStyle(dlg.dirCtrl.GetTreeCtrl().GetWindowStyle() | wx.TR_MULTIPLE) # If the user selects OK, then we process the dialog's data. # This is done by getting the path data from the dialog - BEFORE # we destroy it. if dlg.ShowModal() == wx.ID_OK: #bar = wx.ProgressDialog("Progress dialog example", # "An informative message", # parent=self, # style = wx.PD_CAN_ABORT # | wx.PD_APP_MODAL # | wx.PD_ELAPSED_TIME # | wx.PD_ESTIMATED_TIME # | wx.PD_REMAINING_TIME # ) selected_paths = dlg.GetPaths() for cur_path in selected_paths: # Fix the wrongly added 'Home Directory' in the path returned # by the multidir dialog. if cur_path.startswith('Home directory'): cur_path = cur_path.replace('Home directory', os.getenv('HOME')) matches = [] #count = 0 k = 0 filter_pattern = self.collectionNode.pref_manager.get_value('filter_pattern') for root, dirnames, filenames in os.walk(cur_path, topdown = True): dirnames.sort() self.logger.info('Scanning directory: %s.', root) for cur_pattern in filter_pattern: for filename in fnmatch.filter(filenames, cur_pattern): self.logger.info('Adding file %s', os.path.join(root, filename)) fsize = os.path.getsize(os.path.join(root, filename)); fsize = fsize/(1024.0 * 1024.0) if self.check_file_format is True: # Check the file formats. EPS = ENTRY_POINTS['waveform'] for format_ep in [x for (key, x) in EPS.items() if key == 'MSEED']: # search isFormat for given entry point isFormat = load_entry_point(format_ep.dist.key, 'obspy.plugin.%s.%s' % ('waveform', format_ep.name), 'isFormat') # check format self.logger.debug('Checking format with %s.', isFormat) if isFormat(os.path.join(root,filename)): file_format = format_ep.name break; else: file_format = 'unknown' else: file_format = 'not checked' self.logger.debug('adding to matches') matches.append((file_format, os.path.join(root, filename), '%.2f' % fsize)) k += 1 matches = [x for x in matches if x not in self.file_grid.GetTable().data] self.file_grid.GetTable().data.extend(matches) self.file_grid.GetTable().ResetView() #bar.Destroy() self.file_grid.doResize() # Only destroy a dialog after you're done with it. dlg.Destroy() self.logger.debug('Exiting the onAddDirectory.')
import os import wx import wx.lib.agw.multidirdialog as MDD # Our normal wxApp-derived class, as usual app = wx.App(0) dlg = MDD.MultiDirDialog(None, title="Custom MultiDirDialog", defaultPath=os.getcwd(), agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST) if dlg.ShowModal() != wx.ID_OK: print("You Cancelled The Dialog!") dlg.Destroy() paths = dlg.GetPaths() for indx, path in enumerate(paths): print("Path %d: %s"%(indx+1, path)) dlg.Destroy() app.MainLoop() en nu een regel en nog een regel #
def main(): # root = Tk() # root.withdraw() # file_names = askopenfilenames(initialdir = '/media/NAS/Public/Lucas/') # file_names = root.tk.splitlist(file_names) ## file_name = '/home/roche/MANIP/results/trial 1-4-2015 - SAJ + BL/RESULTS_scenario_14_trial_2_a_1-4-15-21.txt' # root.destroy()* file_names = [] app = wx.App(0) dlg = MDD.MultiDirDialog( None, title="Custom MultiDirDialog", defaultPath= "/media/NAS/Public/Lucas/", # defaultPath="C:/Users/users/Desktop/", agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST) if dlg.ShowModal() != wx.ID_OK: print("You Cancelled The Dialog!") dlg.Destroy() paths = dlg.GetPaths() dlg.Destroy() app.MainLoop() for path in enumerate(paths): directory = path[1] #.replace('Home directory','/home/lucas') filesToAdd = os.listdir(directory) for file in filesToAdd: file_names.append(directory + '/' + file) # file_names_HFO = [x for x in file_names if x.find('_s_')!=-1] # file_names_HFOP = [x for x in file_names if x.find('_a_')!=-1] # file_names_ULTRON = [x for x in file_names if x.find('_u_')!=-1] # file_names_ROBOT = [x for x in file_names if x.find('_r_')!=-1] # file_names_ALONE = [x for x in file_names if x.find('_w_')!=-1] # # file_names = file_names_HFO + file_names_HFOP + file_names_ULTRON + file_names_ROBOT + file_names_ALONE Delta = [] for file in file_names: DataClass = FileData(file) DataClass.getDataFromFile() for n in range(0, len(DataClass.Time) - DataClass.time2line(60)): Delta.append(DataClass.Time[n + 1] - DataClass.Time[n]) print len(Delta), min(Delta), numpy.mean(Delta), max(Delta) print float(len([x for x in Delta if (x < 0.000202 and x > 0.000198) ])) / len(Delta) print float(len([x for x in Delta if (x < 0.00021 and x > 0.00019) ])) / len(Delta) print float(len([x for x in Delta if (x < 0.00022 and x > 0.00018) ])) / len(Delta) # N=100 # compte = [0]*N # compte_pc = [0]*N # T = 1/5000. # for x in Delta: # for n in range(0,N): # low = T*(0.95 + 0.1/N*n) # high = T*(0.95 + 0.1/N*(n+1)) # if x >= low and x < high: # compte[n] += 1 # break # # for n in range(0, len(compte)): # compte_pc[n] = float(compte[n])/len(Delta) # # for n in range(0, len(compte)): # print T*(0.95 + 0.1/N*n), T*(0.95 + 0.1/N*(n+1)), compte[n] # # plt.figure(1) # for n in range(0,N): # plt.plot([T*(0.95 + 0.1/N*n), T*(0.95 + 0.1/N*n)], [0, compte[n]], color='k', linestyle='-', linewidth=2) # # plt.figure(2) # for n in range(0,N): # plt.plot([T*(0.95 + 0.1/N*n), T*(0.95 + 0.1/N*n)], [0, compte_pc[n]], color='k', linestyle='-', linewidth=2) plt.figure() ax = plt.subplot(111) ax.hist(Delta, 100) ax.xaxis.set_ticks_position('none') plt.xlabel("Loop execution time (s)") plt.ylabel("Count") plt.show()
def on_open_multiple_ML_files(self, open_type, pathlist=[]): # http://stackoverflow.com/questions/1252481/sort-dictionary-by-another-dictionary # http://stackoverflow.com/questions/22520739/python-sort-a-dict-by-values-producing-a-list-how-to-sort-this-from-largest-to self.config.ciuMode = 'MANUAL' tempList = self.view.panelMML.filelist tstart = time.clock() if len(pathlist) > 0: dlg = None else: if self.config.lastDir == None or not os.path.isdir( self.config.lastDir): self.config.lastDir = os.getcwd() dlg = MDD.MultiDirDialog(self.view, title="Choose MassLynx files to open:", defaultPath=self.config.lastDir, agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST) if dlg.ShowModal() == wx.ID_OK: pathlist = dlg.GetPaths() if open_type == "multiple_files_add": # Check if current document is a comparison document # If so, it will be used docList = self.checkIfAnyDocumentsAreOfType(type='Type: MANUAL') if len(docList) == 0: self.onThreading(None, ( "Did not find appropriate document. Creating a new one...", 4), action='updateStatusbar') dlg = wx.FileDialog(self.view, "Please select a name for the document", "", "", "", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: path, idName = os.path.split(dlg.GetPath()) else: return # Create document self.docs = documents() self.docs.title = idName self.docs.path = path self.docs.userParameters = self.config.userParameters self.docs.userParameters['date'] = getTime() else: self.selectDocDlg = panelSelectDocument( self.view, self, docList) if self.selectDocDlg.ShowModal() == wx.ID_OK: pass # Check that document exists if self.currentDoc == None: self.onThreading(None, ('Please select a document', 4), action='updateStatusbar') return self.docs = self.documentsDict[self.currentDoc] self.onThreading( None, ('Using document: ' + self.docs.title.encode('ascii', 'replace'), 4), action='updateStatusbar') elif open_type == "multiple_files_new_document": dlg = wx.FileDialog(self.view, "Please select a name for the document", "", "", "", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: path, idName = os.path.split(dlg.GetPath()) else: return # Create document self.docs = documents() self.docs.title = idName self.docs.path = path self.docs.userParameters = self.config.userParameters self.docs.userParameters['date'] = getTime() for i, file_path in enumerate(pathlist): path = self.checkIfRawFile(file_path) if path is None: continue else: try: pathSplit = path.encode('ascii', 'replace').split(':)') start = pathSplit[0].split('(') start = start[-1] path = ''.join([start, ':', pathSplit[1]]) except IndexError: path = path temp, rawfile = os.path.split(path) # Update lastDir with current path self.config.lastDir = path parameters = self.config.importMassLynxInfFile(path=path, manual=True) xlimits = [parameters['startMS'], parameters['endMS']] extract_kwargs = {'return_data': True} msDataX, msDataY = io_waters.rawMassLynx_MS_extract( path=path, driftscope_path=self.config.driftscopePath, **extract_kwargs) extract_kwargs = {'return_data': True} xvalsDT, imsData1D = io_waters.rawMassLynx_DT_extract( path=path, driftscope_path=self.config.driftscopePath, **extract_kwargs) if i <= 15: color = self.config.customColors[i] else: color = randomColorGenerator(True) color = self.view.panelMML.on_check_duplicate_colors( color, document_name=self.docs.title) tempList.Append([ rawfile, str(parameters['trapCE']), self.docs.title, os.path.splitext(rawfile)[0] ]) # name as initial label tempList.SetItemBackgroundColour(tempList.GetItemCount() - 1, convertRGB1to255(color)) self.docs.gotMultipleMS = True self.docs.multipleMassSpectrum[rawfile] = { 'trap': parameters['trapCE'], 'xvals': msDataX, 'yvals': msDataY, 'ims1D': imsData1D, 'ims1DX': xvalsDT, 'xlabel': 'Drift time (bins)', 'xlabels': 'm/z (Da)', 'path': path, 'color': color, 'parameters': parameters, 'xlimits': xlimits } # Sum all mass spectra into one if self.config.ms_enable_in_MML_start: msFilenames = ["m/z"] counter = 0 kwargs = { 'auto_range': self.config.ms_auto_range, 'mz_min': self.config.ms_mzStart, 'mz_max': self.config.ms_mzEnd, 'mz_bin': self.config.ms_mzBinSize, 'linearization_mode': self.config.ms_linearization_mode } msg = "Linearization method: {} | min: {} | max: {} | window: {} | auto-range: {}".format( self.config.ms_linearization_mode, self.config.ms_mzStart, self.config.ms_mzEnd, self.config.ms_mzBinSize, self.config.ms_auto_range) self.onThreading(None, (msg, 4), action='updateStatusbar') for key in self.docs.multipleMassSpectrum: msFilenames.append(key) if counter == 0: msDataX, tempArray = pr_spectra.linearize_data( self.docs.multipleMassSpectrum[key]['xvals'], self.docs.multipleMassSpectrum[key]['yvals'], **kwargs) msList = tempArray else: msDataX, msList = pr_spectra.linearize_data( self.docs.multipleMassSpectrum[key]['xvals'], self.docs.multipleMassSpectrum[key]['yvals'], **kwargs) tempArray = np.concatenate((tempArray, msList), axis=0) counter += 1 # Reshape the list combMS = tempArray.reshape((len(msList), int(counter)), order='F') # Sum y-axis data msDataY = np.sum(combMS, axis=1) msDataY = pr_spectra.normalize_1D(inputData=msDataY) xlimits = [parameters['startMS'], parameters['endMS']] # Form pandas dataframe combMSOut = np.concatenate((msDataX, tempArray), axis=0) combMSOut = combMSOut.reshape((len(msList), int(counter + 1)), order='F') msSaveData = pd.DataFrame(data=combMSOut, columns=msFilenames) # Add data self.docs.gotMSSaveData = True self.docs.massSpectraSave = msSaveData # pandas dataframe that can be exported as csv self.docs.gotMS = True self.docs.massSpectrum = { 'xvals': msDataX, 'yvals': msDataY, 'xlabels': 'm/z (Da)', 'xlimits': xlimits } # Plot name_kwargs = { "document": self.docs.title, "dataset": "Mass Spectrum" } self.view.panelPlots.on_plot_MS(msDataX, msDataY, xlimits=xlimits, **name_kwargs) # Update status bar with MS range self.view.SetStatusText( "{}-{}".format(parameters['startMS'], parameters['endMS']), 1) self.view.SetStatusText("MSMS: {}".format(parameters['setMS']), 2) # Add info to document self.docs.parameters = parameters self.docs.dataType = 'Type: MANUAL' self.docs.fileFormat = 'Format: MassLynx (.raw)' self.OnUpdateDocument(self.docs, 'document') # Show panel self.view.onPaneOnOff(evt=ID_window_multipleMLList, check=True) # Removing duplicates self.view.panelMML.onRemoveDuplicates(evt=None) tend = time.clock() self.onThreading(None, ('Total time to extract %d files was: %.3gs' % (len(pathlist), tend - tstart), 4), action='updateStatusbar')
def main(): # root = Tk() # root.withdraw() # file_names = askopenfilenames(initialdir = '/media/NAS/Public/Lucas/OLD_MANIPS/') # file_names_total = root.tk.splitlist(file_names) # root.destroy() app = wx.App(0) dlg = MDD.MultiDirDialog(None, title="Custom MultiDirDialog", defaultPath="/media/NAS/Public/Lucas/", # defaultPath="C:/Users/users/Desktop/", agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST) if dlg.ShowModal() != wx.ID_OK: print("You Cancelled The Dialog!") dlg.Destroy() paths = dlg.GetPaths() dlg.Destroy() app.MainLoop() file_names_total =[] for path in enumerate(paths): directory= path[1].replace('Home directory','/home/lucas') print(directory) file_names = os.listdir(directory) # for file in file_names: file = directory + '/' + file file_names_total.append(file) expectedChoicesTotal = [] finalChoicesTotal = [] thresh_times = [] print "Threshold\tStartingTime\tStopTime\tSize\taveragetime\tAccuracy\tunknown\ttrueAcc" for k in range (6,7): for j in range(1,2): for l in range(40,45): expectedChoicesTotal = [] finalChoicesTotal = [] thresh_times = [] end_times = [] # fileType = [] for file in file_names_total: DataClass = FileData(file) DataClass.getDataFromFile() if DataClass.fileType != 'HFOP' or file.find('~')!=-1: continue DataClass.threshold = 5*(k+1)*0.8 DataClass.analysisStartTime = 0.2 + j*0.1 # print DataClass.threshold, DataClass.analysisStartTime DataClass.threshold_ext = 0.1*80 (tempE, tempF, tempT, tempET) = DataClass.intentionDetectionST() expectedChoicesTotal.extend(tempE) finalChoicesTotal.extend(tempF) thresh_times.extend(tempT) end_times.extend(tempET) mean_thresh_time = np.mean(thresh_times) thresh_min_time = min(thresh_times) thresh_max_time = max(thresh_times) N = len(finalChoicesTotal) print len(finalChoicesTotal), len(thresh_times), len(end_times) diff = [] for i in range (0, N): try: diff.append(end_times[i] - thresh_times[i]) except: print i # results = [0]*N unknown=0 for i in range (0, N): # print expectedChoicesTotal[i], "\t",finalChoicesTotal[i], "\t",thresh_times[i] if thresh_times[i] > 0.5 + l*0.05: unknown +=1 else: results[i] = expectedChoicesTotal[i] * finalChoicesTotal[i] somme = float(sum(results)) size = float(len(results)) good = (somme+size)/2 # thresh_times_true = [] # thresh_times_false = [] # for i in range (0, N): # if results[i] == 1: # thresh_times_true.append(thresh_times[i]) # elif results[i] == -1: # thresh_times_false.append(thresh_times[i]) # # YT,XT = np.histogram(thresh_times_true, bins=40, range = (0,2)) # YF,XF = np.histogram(thresh_times_false, bins=40, range = (0,2)) # # ## thresh_times = numpy.sort(thresh_times) # plt.figure(DataClass.threshold) ## for i in range(0, N): ## if results[i] == 1: ## plt.plot(thresh_times[i], 0.2+j*0.1, 'g+') ## elif results[i] == -1: ## plt.plot(thresh_times[i], 0.2+j*0.1, 'r+') ## plt.plot(thresh_times, [0.2 + j*0.1]*len(thresh_times), 'b+') # for i in range (0, len(YT)): # if YT.all() == 0 and YF.all() == 0: # continue # plt.plot([XT[i], XT[i]], [0.2+0.1*j, 0.2+0.1*j + float(YT[i])*0.05/max(YT)], 'g-', linewidth = 2, solid_capstyle="round") # plt.plot([XT[i], XT[i+1]],[0.2+0.1*j + float(YT[i])*0.05/max(YT), 0.2+0.1*j + float(YT[i])*0.05/max(YT)], 'g-', linewidth = 2, solid_capstyle="round") # plt.plot([XT[i+1], XT[i+1]], [0.2+0.1*j, 0.2+0.1*j + float(YT[i])*0.05/max(YT)], 'g-', linewidth = 2, solid_capstyle="round") # plt.plot([XF[i], XF[i]], [0.2+0.1*j, 0.2+0.1*j - float(YF[i])*0.05/max(YT)], 'r-', linewidth = 2, solid_capstyle="round") # plt.plot([XF[i], XF[i+1]],[0.2+0.1*j -float(YF[i])*0.05/max(YT), 0.2+0.1*j -float(YF[i])*0.05/max(YT)], 'r-', linewidth = 2, solid_capstyle="round") # plt.plot([XF[i+1], XF[i+1]], [0.2+0.1*j, 0.2+0.1*j - float(YF[i])*0.05/max(YT)], 'r-', linewidth = 2, solid_capstyle="round") # plt.plot([0, 2], [0.2+0.1*j, 0.2+0.1*j], 'k-', linewidth = 1) # plt.plot(mean_thresh_time, 0.2 + j*0.1, 'k+', markersize = 12) # plt.axis([0,2.1,0.1,0.7]) # # count_095 = 0.0 # count_100 = 0.0 # for i in range(0, N): # if thresh_times[i] >= 0.95: # count_095 += 1 # if thresh_times[i] >= 1.0: # count_100 += 1 # count_095 = float(count_095)/N*100 # count_100 = float(count_100)/N*100 accuracy = good/size*100 if unknown != size: true_accuracy = ((2*size*good/size - size)+ (size-unknown))/(2*(size-unknown))*100 else: true_accuracy = 'NAN' print 5*(k+1), "\t", 0.2 + j*0.1, "\t", 0.5 + l*0.05, "\t" ,size, "\t",mean_thresh_time, "\t", accuracy, "\t", unknown/size*100, "\t", true_accuracy, "\t", good , "\t", unknown, np.mean(diff), np.std(diff), min(diff), max(diff) #, "\t",thresh_min_time, "\t",thresh_max_time, "\t",count_095, "\t",count_100 plt.show()
def main(): # root = Tk() # root.withdraw() # file_names = askopenfilenames(initialdir = '~/Documents/Manip') # file_names = root.tk.splitlist(file_names) # root.destroy() plot = 0 app = wx.App(0) dlg = MDD.MultiDirDialog(None, title="Custom MultiDirDialog", defaultPath="/home/lucas/Documents/Manip/", # defaultPath="C:/Users/users/Desktop/", agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST) if dlg.ShowModal() != wx.ID_OK: print("You Cancelled The Dialog!") dlg.Destroy() paths = dlg.GetPaths() dlg.Destroy() app.MainLoop() DATA = pandas.DataFrame(data={'SUBJ_NB': [], 'SUBJ_NAME1' : [], 'SUBJ_NAME2' : [], 'IS_TRAINING':[] , 'EXP_COND' : [], 'TRIAL_NB' : [], 'ST_TIME' : [], 'END_TIME' : [], 'SUBJ_TARGET1' : [], 'SUBJ_TARGET2' : [], 'FINAL_CHOICE' : [], 'FINAL_POS1': [], 'FINAL_POS2': [], 'FINAL_POSC' : [], 'TARGET_WIDTH1' : [], 'TARGET_WIDTH2' : []}) DATA_HIST = pandas.DataFrame(data={'SUBJ_NB':[], 'SUBJ_NAME1' : [], 'SUBJ_NAME2' : [], 'EXP_COND':[], 'HIST':[], 'TRIAL_NB' : [], 'IS_TRAINING':[]}) ###### EXPE ##################################################################################################### for path in enumerate(paths): directory= path[1].replace('Home directory','/home/lucas') filesToAdd = os.listdir(directory) fileName =[] fileType = [] date = [] isTraining = [] for file in filesToAdd: DataClass = FileData(directory + '/' + file) if DataClass.fileName.find('_UI_')!=-1 or DataClass.fileName.find('~')!=-1: continue fileName.append(str(DataClass.fileName)) fileType.append(DataClass.fileType) date.append(DataClass.fileDate) df = pandas.DataFrame(data={'fileName': fileName, 'fileType': fileType, 'date':date}) df = df.sort_values(by=['fileType', 'date']) tempType = '' tempCount = 0 expCond=[] for f in df['fileType']: if f != tempType: expCond.append(f) tempCount = 0 if tempCount < 2: isTraining.append(1) else: isTraining.append(0) tempType = f tempCount +=1 df['isTraining'] = isTraining subj_names = [[],[]] file_counter = 0 ###### COND ##################################################################################################### for cond in expCond: figNb = 0 nb_trial = 0 n_subplots = len(df[df['fileType'] == cond]) l=int(np.sqrt(n_subplots)) if n_subplots-l*l == 0: i_subplots = l j_subplots = l elif n_subplots-l*l <= l: i_subplots = l j_subplots = l+1 elif n_subplots-l*l > l: i_subplots = l+1 j_subplots = l+1 if plot: if cond == 'ALONE': axarr_pos = [[],[]] axarr_vit = [[],[]] f = [0]*4 f[0], axarr_pos[0] = plt.subplots(i_subplots, j_subplots) f[1], axarr_pos[1] = plt.subplots(i_subplots, j_subplots) f[2], axarr_vit[0] = plt.subplots(i_subplots, j_subplots) f[3], axarr_vit[1] = plt.subplots(i_subplots, j_subplots) axarr_pos[0] = np.matrix(axarr_pos[0]) axarr_pos[1] = np.matrix(axarr_pos[1]) axarr_vit[0] = np.matrix(axarr_vit[0]) axarr_vit[1] = np.matrix(axarr_vit[1]) else: f[0], axarr_pos[0] = plt.subplots(i_subplots, j_subplots) f[2], axarr_vit[0] = plt.subplots(i_subplots, j_subplots) axarr_pos[0] = np.matrix(axarr_pos[0]) axarr_vit[0] = np.matrix(axarr_vit[0]) nb_subjects = 2 file_counter = 0 hist_vit = [[],[],[]] hist_vit[0] = np.array([0]*101) hist_vit[1] = np.array([0]*101) hist_vit[2] = np.array([0]*101) ###### FILES ##################################################################################################### for file in df[df['fileType'] == cond]['fileName']: print file DataClass = FileData(file) DataClass.getDataFromFile() N = len(DataClass.Time) DataClass.getDataFromUIFile() subj_names[0] = DataClass.SUBJECT_NAMES[0] subj_names[1] = DataClass.SUBJECT_NAMES[1] nb_subjects = DataClass.UINbSubjects if plot: if cond == 'ALONE': f[0].suptitle(subj_names[0]) f[1].suptitle(subj_names[1]) f[2].suptitle(subj_names[0]) f[3].suptitle(subj_names[1]) else: f[0].suptitle(subj_names[0]+'+'+subj_names[1]) f[2].suptitle(subj_names[0]+'+'+subj_names[1]) nyq = 0.5*5000 low = 10/nyq b, a = sig.butter(6, low, btype = 'low') b2, a2 = sig.butter(2, 50/nyq, btype = 'low') t0 = 0#int(2/DataClass.Time[N-1]*N) tf = N#int(25/DataClass.Time[N-1]*N) #Applying Butterworth filer to force signals for1 = sig.lfilter(b, a, DataClass.Subj_for1) for2 = sig.lfilter(b, a, DataClass.Subj_for2) pos = [[],[]] pos[0] = sig.lfilter(b2, a2, DataClass.Subj_pos1) pos[1] = sig.lfilter(b2, a2, DataClass.Subj_pos2) posC = sig.lfilter(b2, a2, DataClass.Curs_pos) vit = [[],[]] vit[0] = [0]*N vit[1] = [0]*N vitC = [0]*N for i in range(4,N-4): vit[0][i] = 1./280*pos[0][i-4] - 4./105*pos[0][i-3] + 1./5*pos[0][i-2] - 4./5*pos[0][i-1] + 4./5*pos[0][i+1] - 1./5*pos[0][i+2] + 4./105*pos[0][i+3] - 1./280*pos[0][i+4] vit[1][i] = 1./280*pos[1][i-4] - 4./105*pos[1][i-3] + 1./5*pos[1][i-2] - 4./5*pos[1][i-1] + 4./5*pos[1][i+1] - 1./5*pos[1][i+2] + 4./105*pos[1][i+3] - 1./280*pos[1][i+4] if cond == 'HFOP' or cond == 'HFO': vitC[i] = 1./280*posC[i-4] - 4./105*posC[i-3] + 1./5*posC[i-2] - 4./5*posC[i-1] + 4./5*posC[i+1] - 1./5*posC[i+2] + 4./105*posC[i+3] - 1./280*posC[i+4] indices_trial = [0] indices_phase = [[],[]] indices_phase[0] = [0] indices_phase[1] = [0] for i in range(0, N-1): if DataClass.TimeTrial[i] > 0.05 and DataClass.TimeTrial[i+1] < 0.05: indices_trial.append(i+1) if DataClass.TimePhase1[i] > 0.05 and DataClass.TimePhase1[i+1] < 0.05: indices_phase[0].append(i+1) if DataClass.TimePhase2[i] > 0.05 and DataClass.TimePhase2[i+1] < 0.05: indices_phase[1].append(i+1) # indices_trial.append(N-1) indices_phase[0].append(N-1) indices_phase[1].append(N-1) ################## EXTRACT START AND END TIMES + VELOCITIES HISTOGRAMS #######################" if cond=='ALONE': for k in range(0,nb_subjects): st_timesC = [] end_timesC = [] st_timesF = [] end_timesF = [] for i in range(0, len(DataClass.UITrialNumber)): t0 = indices_trial[2*i+1] tf = indices_phase[k][4*i+3]- DataClass.time2line(1) tempST = 0 tempEND = 0 if DataClass.UIFinalChoice[k][i] == DataClass.UITargetPosC[i]: final_target = DataClass.UITargetPosC[i] target_width = DataClass.UITargetWidth[0] for j in range(t0, tf): if abs(pos[k][j-1] - DataClass.UIStartPos[i]) < DataClass.UIStartWidth and abs(pos[k][j] - DataClass.UIStartPos[i]) > DataClass.UIStartWidth: tempST = DataClass.Time[j-t0] tempEND = DataClass.Time[tf-t0] st_timesC.append(tempST) end_timesC.append(tempEND) elif DataClass.UIFinalChoice[k][i] == DataClass.UITargetPosF[i]: final_target = DataClass.UITargetPosF[i] target_width = DataClass.UITargetWidth[1] for j in range(t0, tf): if abs(pos[k][j-1] - DataClass.UIStartPos[i]) < DataClass.UIStartWidth and abs(pos[k][j] - DataClass.UIStartPos[i]) > DataClass.UIStartWidth: tempST = DataClass.Time[j-t0] tempEND = DataClass.Time[tf-t0] st_timesF.append(tempST) end_timesF.append(tempEND) else: final_target = 0 target_width = 0 tempdf = pandas.DataFrame(data={'SUBJ_NB': [k], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'IS_TRAINING':[int(df[df['fileName']==file]['isTraining'])] , 'EXP_COND' : [DataClass.fileType], 'TRIAL_NB' : [file_counter], 'ST_TIME' : [tempST], 'END_TIME' : [tempEND], 'SUBJ_TARGET1' : [DataClass.UITargetSubj[0][i]], 'SUBJ_TARGET2' : [DataClass.UITargetSubj[1][i]], 'FINAL_CHOICE' : [DataClass.UIFinalChoice[k][i]], 'FINAL_POS1': [pos[0][tf+DataClass.time2line(1)]], 'FINAL_POS2': [pos[1][tf+DataClass.time2line(1)]], 'FINAL_POSC' : ['-'], 'TARGET_WIDTH1' : [DataClass.UITargetWidth[0][i]], 'TARGET_WIDTH2' : [DataClass.UITargetWidth[1][i]] }) DATA = DATA.append(tempdf, ignore_index=True) # if(not(int(df[df['fileName']==file]['isTraining']))): # temp_hist, temp_bins = np.histogram([x for x in vit[k][t0:tf] if abs(x)>0.01], bins=101, range=(-0.75,1.5)) # hist_vit[k] = np.add(hist_vit[k], temp_hist) temp_hist, temp_bins = np.histogram([x for x in vit[k][t0:tf] if abs(x)>0.01], bins=101, range=(-0.75,1.5)) if np.sum(temp_hist)!=0: temp_hist = [float(x)/float(np.sum(temp_hist)) for x in temp_hist] else: temp_hist = [float(x) for x in temp_hist] tempdf = pandas.DataFrame(data={'SUBJ_NB':[k], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'EXP_COND':[cond], 'HIST':[temp_hist], 'TRIAL_NB' : [file_counter], 'IS_TRAINING':[int(df[df['fileName']==file]['isTraining'])]}) DATA_HIST = DATA_HIST.append(tempdf,ignore_index=True) elif cond=='HFOP': st_timesC = [] end_timesC = [] st_timesF = [] end_timesF = [] for i in range(0, len(DataClass.UITrialNumber)): t0 = indices_trial[2*i+1] tf = indices_phase[0][4*i+3]- DataClass.time2line(1) tempST = 0 tempEND = 0 if DataClass.UIFinalChoice[0][i] == DataClass.UITargetPosC[i]: final_target = DataClass.UITargetPosC[i] target_width = DataClass.UITargetWidth[0] for j in range(t0, tf): if abs(posC[j-1] - DataClass.UIStartPos[i]) < DataClass.UIStartWidth and abs(posC[j] - DataClass.UIStartPos[i]) > DataClass.UIStartWidth: tempST = DataClass.Time[j-t0] tempEND = DataClass.Time[tf-t0] st_timesC.append(tempST) end_timesC.append(tempEND) elif DataClass.UIFinalChoice[0][i] == DataClass.UITargetPosF[i]: final_target = DataClass.UITargetPosF[i] target_width = DataClass.UITargetWidth[1] for j in range(t0, tf): if abs(posC[j-1] - DataClass.UIStartPos[i]) < DataClass.UIStartWidth and abs(posC[j] - DataClass.UIStartPos[i]) > DataClass.UIStartWidth: tempST = DataClass.Time[j-t0] tempEND = DataClass.Time[tf-t0] st_timesF.append(tempST) end_timesF.append(tempEND) else: final_target = 0 target_width = 0 tempdf = pandas.DataFrame(data={'SUBJ_NB': [2], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'IS_TRAINING':[int(df[df['fileName']==file]['isTraining'])] , 'EXP_COND' : [DataClass.fileType], 'TRIAL_NB' : [file_counter], 'ST_TIME' : [tempST], 'END_TIME' : [tempEND], 'SUBJ_TARGET1' : [DataClass.UITargetSubj[0][i]], 'SUBJ_TARGET2' : [DataClass.UITargetSubj[1][i]], 'FINAL_CHOICE' : [DataClass.UIFinalChoice[0][i]], 'FINAL_POS1': [pos[0][tf+DataClass.time2line(1)]], 'FINAL_POS2': [pos[1][tf+DataClass.time2line(1)]], 'FINAL_POSC' : [posC[tf+DataClass.time2line(1)]], 'TARGET_WIDTH1' : [DataClass.UITargetWidth[0][i]], 'TARGET_WIDTH2' : [DataClass.UITargetWidth[1][i]]}) DATA = DATA.append(tempdf, ignore_index=True) # if(not(int(df[df['fileName']==file]['isTraining']))): # temp_hist, temp_bins = np.histogram([x for x in vitC[t0:tf] if abs(x)>0.01], bins=101, range=(-0.75,1.5)) # hist_vit[2] = np.add(hist_vit[2], temp_hist) temp_hist, temp_bins = np.histogram([x for x in vitC[t0:tf] if abs(x)>0.01], bins=101, range=(-0.75,1.5)) if np.sum(temp_hist)!=0: temp_hist = [float(x)/float(np.sum(temp_hist)) for x in temp_hist] else: temp_hist = [float(x) for x in temp_hist] tempdf = pandas.DataFrame(data={'SUBJ_NB':[2], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'EXP_COND':[cond], 'HIST':[temp_hist], 'TRIAL_NB' : [file_counter], 'IS_TRAINING':[int(df[df['fileName']==file]['isTraining'])]}) DATA_HIST = DATA_HIST.append(tempdf,ignore_index=True) elif cond=='HFO': st_timesC = [] end_timesC = [] st_timesF = [] end_timesF = [] for i in range(0, len(DataClass.UITrialNumber)): t0 = indices_trial[2*i+1] tf = indices_phase[0][4*i+3]- DataClass.time2line(1) tempST = 0 tempEND = 0 if DataClass.UIFinalChoice[0][i] == DataClass.UITargetPosC[i]: final_target = DataClass.UITargetPosC[i] target_width = DataClass.UITargetWidth[0] for j in range(t0, tf): if abs(posC[j-1] - DataClass.UIStartPos[i]) < DataClass.UIStartWidth and abs(posC[j] - DataClass.UIStartPos[i]) > DataClass.UIStartWidth: tempST = DataClass.Time[j-t0] tempEND = DataClass.Time[tf-t0] st_timesC.append(tempST) end_timesC.append(tempEND) elif DataClass.UIFinalChoice[0][i] == DataClass.UITargetPosF[i]: final_target = DataClass.UITargetPosF[i] target_width = DataClass.UITargetWidth[1] for j in range(t0, tf): if abs(posC[j-1] - DataClass.UIStartPos[i]) < DataClass.UIStartWidth and abs(posC[j] - DataClass.UIStartPos[i]) > DataClass.UIStartWidth: tempST = DataClass.Time[j-t0] tempEND = DataClass.Time[tf-t0] st_timesF.append(tempST) end_timesF.append(tempEND) else: final_target = 0 target_width = 0 tempdf = pandas.DataFrame(data={'SUBJ_NB': [2], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'IS_TRAINING':[int(df[df['fileName']==file]['isTraining'])] , 'EXP_COND' : [DataClass.fileType], 'TRIAL_NB' : [file_counter], 'ST_TIME' : [tempST], 'END_TIME' : [tempEND], 'SUBJ_TARGET1' : [DataClass.UITargetSubj[0][i]], 'SUBJ_TARGET2' : [DataClass.UITargetSubj[1][i]], 'FINAL_CHOICE' : [DataClass.UIFinalChoice[0][i]], 'FINAL_POS1': [pos[0][tf+DataClass.time2line(1)]], 'FINAL_POS2': [pos[1][tf+DataClass.time2line(1)]], 'FINAL_POSC' : [posC[tf+DataClass.time2line(1)]], 'TARGET_WIDTH1' : [DataClass.UITargetWidth[0][i]], 'TARGET_WIDTH2' : [DataClass.UITargetWidth[1][i]]}) DATA = DATA.append(tempdf, ignore_index=True) # if(not(int(df[df['fileName']==file]['isTraining']))): # temp_hist, temp_bins = np.histogram([x for x in vit[0][t0:tf] if abs(x)>0.01], bins=101, range=(-0.75,1.5)) # hist_vit[0] = np.add(hist_vit[0], temp_hist) # temp_hist, temp_bins = np.histogram([x for x in vit[1][t0:tf] if abs(x)>0.01], bins=101, range=(-0.75,1.5)) # hist_vit[1] = np.add(hist_vit[1], temp_hist) # temp_hist, temp_bins = np.histogram([x for x in vitC[t0:tf] if abs(x)>0.01], bins=101, range=(-0.75,1.5)) # hist_vit[2] = np.add(hist_vit[2], temp_hist) for k in range(0, nb_subjects): temp_hist, temp_bins = np.histogram([x for x in vit[k][t0:tf] if abs(x)>0.01], bins=101, range=(-0.75,1.5)) if np.sum(temp_hist)!=0: temp_hist = [float(x)/float(np.sum(temp_hist)) for x in temp_hist] else: temp_hist = [float(x) for x in temp_hist] tempdf = pandas.DataFrame(data={'SUBJ_NB':[k], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'EXP_COND':[cond], 'HIST':[temp_hist], 'TRIAL_NB' : [file_counter], 'IS_TRAINING':[int(df[df['fileName']==file]['isTraining'])]}) DATA_HIST = DATA_HIST.append(tempdf,ignore_index=True) temp_hist, temp_bins = np.histogram([x for x in vitC[t0:tf] if abs(x)>0.01], bins=101, range=(-0.75,1.5)) temp_hist = [float(x)/float(np.sum(temp_hist)) for x in temp_hist] tempdf = pandas.DataFrame(data={'SUBJ_NB':[2], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'EXP_COND':[cond], 'HIST':[temp_hist], 'TRIAL_NB' : [file_counter], 'IS_TRAINING':[int(df[df['fileName']==file]['isTraining'])]}) DATA_HIST = DATA_HIST.append(tempdf,ignore_index=True) # print "Subject : ", k # print "Mean Start Time Target C : ", np.mean(st_timesC) # print "Mean End Time Target C : ", np.mean(end_timesC) # print "Mean Start Time Target F : ", np.mean(st_timesF) # print "Mean End Time Target F : ", np.mean(end_timesF) # print "Mean Traj Time Target C : ", np.mean([end_timesC[i] - st_timesC[i] for i in range(0, len(st_timesC))]) # print "Mean Traj Time Target F : ", np.mean([end_timesF[i] - st_timesF[i] for i in range(0, len(st_timesF))]) # print ("\n") ########################PLOTS ######################### if plot: if cond == 'ALONE': ## PLOT POSITIONS pos_targetC = [DataClass.UITargetPosC[0]]*(tf-t0) pos_targetF = [DataClass.UITargetPosF[0]]*(tf-t0) pos_start = [DataClass.UIStartPos[0]]*(tf-t0) width_tC = DataClass.UITargetWidthC width_tF = DataClass.UITargetWidthF for k in range(0,nb_subjects): plt.figure(f[k].number) figNb+=1 # axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots] = plt.subplot(111) axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].axis([0, DataClass.WINDOW_WIDTH, 0, 2]) temp1 = [] temp2 = [] for i in range(0, len(DataClass.UITrialNumber)): t0 = indices_trial[2*i+1] tf = indices_phase[k][4*i+3]- DataClass.time2line(1) time_local = [ x - DataClass.Time[t0] for x in DataClass.Time[t0:tf]] pos_targetC = [DataClass.UITargetPosC[0]]*(tf-t0) pos_targetF = [DataClass.UITargetPosF[0]]*(tf-t0) pos_start = [DataClass.UIStartPos[0]]*(tf-t0) axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(pos_targetC, time_local,'k') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x-width_tC for x in pos_targetC], time_local,'k--') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x+width_tC for x in pos_targetC], time_local,'k--') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(pos_targetF, time_local,'k') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x-width_tF for x in pos_targetF], time_local,'k--') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x+width_tF for x in pos_targetF], time_local,'k--') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(pos_start, time_local,'k') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x-10 for x in pos_start], time_local,'k--') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x+10 for x in pos_start], time_local,'k--') if DataClass.UIFinalChoice[k][i] == DataClass.UITargetPosC[i]: # axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[indices_phase[0][2*i+1]]-DataClass.Time[t0], DataClass.Time[indices_phase[0][2*i+1]]-DataClass.Time[t0]], 'r--') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[tf]-DataClass.Time[t0], DataClass.Time[tf]-DataClass.Time[t0]], 'g--') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(pos[k][t0:tf], time_local,'g') temp1.append(tf-t0) elif DataClass.UIFinalChoice[k][i] == DataClass.UITargetPosF[i]: axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[tf]-DataClass.Time[t0], DataClass.Time[tf]-DataClass.Time[t0]], 'b--') axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(pos[k][t0:tf], time_local,'b') temp2.append(tf-t0) axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[int(np.mean(temp1))], DataClass.Time[int(np.mean(temp1))]], 'g-', linewidth=3) axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[int(np.mean(temp2))], DataClass.Time[int(np.mean(temp2))]], 'b-', linewidth=3) ## PLOT VITESSES for k in range(0,nb_subjects): plt.figure(f[k+2].number) figNb+=1 for i in range(0, len(DataClass.UITrialNumber)): t0 = indices_trial[2*i+1] tf = indices_phase[k][4*i+3]- DataClass.time2line(1) time_local = [ x - DataClass.Time[t0] for x in DataClass.Time[t0:tf]] if DataClass.UIFinalChoice[k][i] == DataClass.UITargetPosC[i]: axarr_vit[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(vit[k][t0:tf], time_local,'g') temp1.append(tf-t0) elif DataClass.UIFinalChoice[k][i] == DataClass.UITargetPosF[i]: axarr_vit[k][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(vit[k][t0:tf], time_local,'b') temp2.append(tf-t0) elif cond == 'HFOP': ## PLOT POSITIONS pos_targetC = [DataClass.UITargetPosC[0]]*(tf-t0) pos_targetF = [DataClass.UITargetPosF[0]]*(tf-t0) pos_start = [DataClass.UIStartPos[0]]*(tf-t0) width_tC = DataClass.UITargetWidthC width_tF = DataClass.UITargetWidthF plt.figure(f[0].number) figNb+=1 # axarr_pos[k][int(nb_trial/j_subplots), nb_trial%j_subplots] = plt.subplot(111) axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].axis([0, DataClass.WINDOW_WIDTH, 0, 2]) temp1 = [] temp2 = [] for i in range(0, len(DataClass.UITrialNumber)): t0 = indices_trial[2*i+1] tf = indices_phase[0][4*i+3]- DataClass.time2line(1) time_local = [ x - DataClass.Time[t0] for x in DataClass.Time[t0:tf]] pos_targetC = [DataClass.UITargetPosC[0]]*(tf-t0) pos_targetF = [DataClass.UITargetPosF[0]]*(tf-t0) pos_start = [DataClass.UIStartPos[0]]*(tf-t0) axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(pos_targetC, time_local,'k') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x-width_tC for x in pos_targetC], time_local,'k--') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x+width_tC for x in pos_targetC], time_local,'k--') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(pos_targetF, time_local,'k') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x-width_tF for x in pos_targetF], time_local,'k--') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x+width_tF for x in pos_targetF], time_local,'k--') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(pos_start, time_local,'k') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x-10 for x in pos_start], time_local,'k--') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([x+10 for x in pos_start], time_local,'k--') if DataClass.UIFinalChoice[0][i] == DataClass.UITargetPosC[i]: # axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[indices_phase[0][2*i+1]]-DataClass.Time[t0], DataClass.Time[indices_phase[0][2*i+1]]-DataClass.Time[t0]], 'r--') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[tf]-DataClass.Time[t0], DataClass.Time[tf]-DataClass.Time[t0]], 'g--') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(posC[t0:tf], time_local,'g') temp1.append(tf-t0) elif DataClass.UIFinalChoice[0][i] == DataClass.UITargetPosF[i]: axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[tf]-DataClass.Time[t0], DataClass.Time[tf]-DataClass.Time[t0]], 'b--') axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(posC[t0:tf], time_local,'b') temp2.append(tf-t0) axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[int(np.mean(temp1))], DataClass.Time[int(np.mean(temp1))]], 'g-', linewidth=3) axarr_pos[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot([0, DataClass.WINDOW_WIDTH],[DataClass.Time[int(np.mean(temp2))], DataClass.Time[int(np.mean(temp2))]], 'b-', linewidth=3) ## PLOT VITESSES plt.figure(f[2].number) figNb+=1 for i in range(0, len(DataClass.UITrialNumber)): t0 = indices_trial[2*i+1] tf = indices_phase[0][4*i+3]- DataClass.time2line(1) time_local = [ x - DataClass.Time[t0] for x in DataClass.Time[t0:tf]] if DataClass.UIFinalChoice[0][i] == DataClass.UITargetPosC[i]: axarr_vit[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(vitC[t0:tf], time_local,'g') temp1.append(tf-t0) elif DataClass.UIFinalChoice[0][i] == DataClass.UITargetPosF[i]: axarr_vit[0][int(nb_trial/j_subplots), nb_trial%j_subplots].plot(vitC[t0:tf], time_local,'b') temp2.append(tf-t0) file_counter+=1 nb_trial+=1 ###### FILES ##################################################################################################### # if cond=='ALONE': # for k in range(0, nb_subjects): # hist_vit[k] = [float(x)/float(np.sum(hist_vit[k])) for x in hist_vit[k]] # tempdf = pandas.DataFrame(data={'SUBJ_NB':[k], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'EXP_COND':[cond], 'HIST':[hist_vit[k]]}) # DATA_HIST = DATA_HIST.append(tempdf,ignore_index=True) # elif cond=='HFOP': # hist_vit[2] = [float(x)/float(np.sum(hist_vit[2])) for x in hist_vit[2]] # tempdf = pandas.DataFrame(data={'SUBJ_NB':[2], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'EXP_COND':[cond], 'HIST':[hist_vit[2]]}) # DATA_HIST = DATA_HIST.append(tempdf,ignore_index=True) # elif cond=='HFO': # for k in range(0, nb_subjects+1): # hist_vit[k] = [float(x)/float(np.sum(hist_vit[k])) for x in hist_vit[k]] # tempdf = pandas.DataFrame(data={'SUBJ_NB':[k], 'SUBJ_NAME1':[subj_names[0]], 'SUBJ_NAME2': [subj_names[1]], 'EXP_COND':[cond], 'HIST':[hist_vit[k]]}) # DATA_HIST = DATA_HIST.append(tempdf,ignore_index=True) ###### COND ##################################################################################################### ###### EXPE ##################################################################################################### print DATA print DATA_HIST # for i in range(0, len(DATA_HIST['HIST'])): # plt.figure() # if(DATA_HIST['SUBJ_NB'][i]==0): # plt.title(DATA_HIST['EXP_COND'][i] + ' : ' + DATA_HIST['SUBJ_NAME1'][i]) # elif(DATA_HIST['SUBJ_NB'][i]==1): # plt.title(DATA_HIST['EXP_COND'][i] + ' : ' + DATA_HIST['SUBJ_NAME2'][i]) # elif(DATA_HIST['SUBJ_NB'][i]==2): # plt.title(DATA_HIST['EXP_COND'][i] + ' : ' + DATA_HIST['SUBJ_NAME1'][i]+'+'+DATA_HIST['SUBJ_NAME2'][i]) # plt.plot(np.linspace(-0.75, 1.5, 101), DATA_HIST['HIST'][i]) date = time.gmtime(None) date = str(date.tm_mday) + "-" + str(date.tm_mon) + "-" + str(date.tm_hour+2) + "-" + str(date.tm_min) DATA.to_csv('~/Documents/Manip/DATA_POINTING_choices_'+date+'.csv') DATA_HIST.to_csv('~/Documents/Manip/DATA_POINTING_histograms_'+date+'.csv') plt.show(block='False')
def __init__(self, pof, b_verbose, b_detail, b_byfile, b_recur, b_exem, ex_fo, ex_fi, sort, *args, **kwargs): """Builder gui""" # Master gui super().__init__(*args, **kwargs) self.withdraw() # Hide GUI self.iconbitmap(fr'{PATH_PICTURE}/icon.ico') self.title('Pyline counter') # Size and coordinate w = 1200 h = 800 ws = self.winfo_screenwidth() # width of the screen hs = self.winfo_screenheight() # height of the screen x = int((ws / 2) - (w / 2)) y = int((hs / 2) - (h / 2)) self.geometry(f"{w}x{h}+{x}+{y}") # Defaults attributes self.la_th = Thread() self.b_cancel = False # Custom multi directory dialog self.dlg = mdd.MultiDirDialog(None, message="Select one or more " "folders", defaultPath=PATH_PROJECT, agwStyle=mdd.DD_MULTIPLE | mdd.DD_DIR_MUST_EXIST) # Label / Buttons select pof frame_pof = tk.Frame(self) frame_pof.pack(anchor=tk.W, padx=2, pady=3) tk.Label(frame_pof, text="Select").pack(side=tk.LEFT) tk.Button(frame_pof, text="path", command=self.button_browse_path).pack(side=tk.LEFT) tk.Label(frame_pof, text="or").pack(side=tk.LEFT) tk.Button(frame_pof, text="file", command=self.button_browse_file).pack(side=tk.LEFT) tk.Label(frame_pof, text=":").pack(side=tk.LEFT) self.label_pof = tk.StringVar() self.label_pof.trace('w', self.prerequisite_analysis) tk.Entry(frame_pof, width=90, textvariable=self.label_pof).pack(side=tk.LEFT) # Checkbutton option self.option = [ [ "verbose (-v) : Increases the level of verbosity for " "debugging.", tk.BooleanVar(value=b_verbose) ], [ "detail (-d) : Display detail information (number of " "Class/Decorator/Function/Docstring/Comment/Blank " "line).", tk.BooleanVar(value=b_detail) ], [ "byfile (-b) : Display information by file (one " "more line for the total).", tk.BooleanVar(value=b_byfile) ], [ "recursive (-r) : Search files in subfolders (path " "only).", tk.BooleanVar(value=b_recur) ], [ "exclude_empty (-e) : Exclude empty files " "from result.", tk.BooleanVar(value=b_exem) ] ] frame_option = tk.Frame(self) frame_option.pack(anchor=tk.W) for name, b_etat in self.option: check = tk.Checkbutton(frame_option, text=name, variable=b_etat) check.pack(anchor=tk.W) # Option -o (exclude folder) and -i (exclude file) self.option_ex_fo = tk.BooleanVar() self.label_ex_fo = tk.StringVar() self.option_ex_fi = tk.BooleanVar() self.label_ex_fi = tk.StringVar() l_ex = [[ self.option_ex_fo, self.label_ex_fo, self.lab_ex_fo, self.button_ex_fo, self.checkbox_option_ex_fo, ex_fo, "exclude_folder (-o) :", "Exclude folders", "from analysis (recursive option must be enabled; regex " "default pattern:'.*\\your_input\\.*'; delimiter:';') :", 65 ], [ self.option_ex_fi, self.label_ex_fi, self.lab_ex_fi, self.button_ex_fi, self.checkbox_option_ex_fi, ex_fi, "exclude_file (-i) :", "Exclude files", "from analysis (path only; regex default pattern:" "'^your_input$'; delimiter:';') :", 70 ]] for el in l_ex: frame = tk.Frame(self) frame.pack(anchor=tk.W) el[1].trace('w', el[2]) tk.Checkbutton(frame, text=el[6], variable=el[0]).pack(anchor=tk.W, side=tk.LEFT) tk.Button(frame, text=el[7], command=el[3]).pack(side=tk.LEFT) lab = tk.Label(frame, text=el[8]) lab.pack(side=tk.LEFT, expand=True) lab.bind("<Button-1>", el[4]) tk.Entry(frame, width=el[9], textvariable=el[1]).pack(side=tk.LEFT) el[1].set(el[5]) # Option -s (sort) frame_sort = tk.Frame(self) frame_sort.pack(anchor=tk.W) self.option_sort = tk.BooleanVar() self.select_sort = tk.StringVar() self.select_sort.trace('w', self.str_sort) tk.Checkbutton(frame_sort, text="sort (-s) : Sort the " "result by (byfile option must be " "enabled) :", variable=self.option_sort).pack(anchor=tk.W, side=tk.LEFT) combo_sort = ttk.Combobox(frame_sort, width=8, textvariable=self.select_sort, state="readonly") combo_sort.bind("<<ComboboxSelected>>", lambda e: frame_sort.focus()) combo_sort.config(values=("file", "nb", "class", "deco", "func", "doc", "com", "blank", "_file", "_nb", "_class", "_deco", "_func", "_doc", "_com", "_blank")) combo_sort.pack(side=tk.LEFT) self.select_sort.set(sort) if not sort: combo_sort.current(0) self.option_sort.set(False) # Button analysis and clear text result frame_analysis = tk.Frame(self) frame_analysis.pack(pady=(30, 0)) self.button_analysis = tk.Button(frame_analysis, text="Start analysis", command=self.button_sc_analysis) self.button_clear = tk.Button(frame_analysis, text="Clear result", command=self.button_clear_result) self.label_pof.set(pof) # Disable button analysis if empty self.button_analysis.pack(side=tk.LEFT, padx=30) self.button_clear.pack(side=tk.LEFT) # Progressbar frame_progress = tk.Frame(self) frame_progress.pack(fill=tk.BOTH, pady=(15, 0)) self.progress_var = tk.DoubleVar() self.progress_style = ttk.Style(self) self.progress_style.layout( # add label in the layout 'text.Horizontal.TProgressbar', [('Horizontal.Progressbar.trough', { 'children': [('Horizontal.Progressbar.pbar', { 'side': 'left', 'sticky': 'ns' })], 'sticky': 'nswe' }), ('Horizontal.Progressbar.label', { 'sticky': '' })]) self.progress_style.configure( # set initial text 'text.Horizontal.TProgressbar', text=PROGRESS_DEFAULT) self.progress = ttk.Progressbar(frame_progress, style='text.Horizontal' '.TProgressbar', variable=self.progress_var) self.progress.pack(fill=tk.BOTH) # Text result self.text_scroll = GuiTextScrollCombo() self.text_scroll.pack(fill=tk.BOTH, expand=True) self.textvar_result = tk.StringVar() self.textvar_result.trace('w', self.display_result) self.textvar_result.set('') # Disable button clear # Display GUI self.update() self.deiconify()
def test_lib_agw_multidirdialogCtor(self): dlg = MDD.MultiDirDialog(self.frame, title="Custom MultiDirDialog", agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST)
def main(): # Our normal wxApp-derived class, as usual app = wx.App(0) dlg = MDD.MultiDirDialog( None, title="Custom MultiDirDialog", defaultPath= "/home/lucas/Documents/Manip/", # defaultPath="C:/Users/users/Desktop/", agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST) if dlg.ShowModal() != wx.ID_OK: print("You Cancelled The Dialog!") dlg.Destroy() paths = dlg.GetPaths() dlg.Destroy() app.MainLoop() nbChoicesS1tot = [] nbChoicesR1tot = [] nbChoicesS2tot = [] nbChoicesR2tot = [] nameS1tot = [] nameS2tot = [] fileTypetot = [] expeNbtot = [] expe_nb = 0 for path in enumerate(paths): directory = path[1].replace('Home directory', '/home/lucas') print(directory) file_names = os.listdir(directory) file_names_HFO = [ x for x in file_names if x.find('_HFO_') != -1 or x.find('_s_') != -1 ] file_names_HFOP = [ x for x in file_names if x.find('_HFOP_') != -1 or x.find('_a_') != -1 ] file_names_HVP = [ x for x in file_names if x.find('_HRP_') != -1 or x.find('_HVP_') != -1 or x.find('_u_') != -1 ] file_names_KVP = [ x for x in file_names if x.find('_KRP_') != -1 or x.find('_KVP_') != -1 ] file_names_ALONE = [ x for x in file_names if x.find('_Alone_') != -1 or x.find('_w_') != -1 ] # file_names = file_names_HFO + file_names_HFOP + file_names_HVP + file_names_KVP nbChoicesS1 = [] nbChoicesR1 = [] nbChoicesS2 = [] nbChoicesR2 = [] nameS1 = [] nameS2 = [] fileType = [] expeNb = [] d = 0 for file in file_names: file = directory + '/' + file if file.find('~') != -1: # or f.find('trial_1') != -1: d += 1 continue DataClass = FileData(file) DataClass.getDataFromFile() DataClass.analyzeDominance() expeNb.append(expe_nb) fileType.append(DataClass.fileType) nameS1.append(DataClass.SUBJECT_NAME1) nameS2.append(DataClass.SUBJECT_NAME2) if DataClass.fileType == 'HFOP' or DataClass.fileType == 'HFO' or DataClass.fileType == 'HFOP_mou': nbChoicesS1.append(DataClass.nbChoices1) nbChoicesS2.append(DataClass.nbChoices2) nbChoicesR1.append(0) nbChoicesR2.append(0) elif DataClass.fileType == 'HVP' or DataClass.fileType == 'KVP': nbChoicesS1.append(DataClass.nbChoicesH1) nbChoicesR1.append(DataClass.nbChoicesR1) nbChoicesS2.append(DataClass.nbChoicesH2) nbChoicesR2.append(DataClass.nbChoicesR2) print file, " analyzed ... " expe_nb += 1 nbChoicesS1tot.extend(nbChoicesS1) nbChoicesR1tot.extend(nbChoicesR1) nbChoicesS2tot.extend(nbChoicesS2) nbChoicesR2tot.extend(nbChoicesR2) nameS1tot.extend(nameS1) nameS2tot.extend(nameS2) fileTypetot.extend(fileType) expeNbtot.extend(expeNb) data = pandas.DataFrame({ 'EXPE': expeNb, 'TYPE': fileType, 'Name1': nameS1, 'Name2': nameS2, 'Choices1': nbChoicesS1, 'Choices2': nbChoicesS2, 'Robot1': nbChoicesR1, 'Robot2': nbChoicesR2 }) plt.figure(data['Name1'][0] + '+' + data['Name2'][1]) #HFOP labels = data['Name1'][0], data['Name2'][0] sizes = [ np.mean(data[data['TYPE'] == 'HFOP']['Choices1']), np.mean(data[data['TYPE'] == 'HFOP']['Choices2']) ] ax1 = plt.subplot(321) ax1.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['blue', 'red'], startangle=90) ax1.axis('equal' ) # Equal aspect ratio ensures that pie is drawn as a circle. #HFO labels = data['Name1'][0], data['Name2'][0] sizes = [ np.mean(data[data['TYPE'] == 'HFO']['Choices1']), np.mean(data[data['TYPE'] == 'HFO']['Choices2']) ] ax2 = plt.subplot(322) ax2.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['blue', 'red'], startangle=90) ax2.axis('equal' ) # Equal aspect ratio ensures that pie is drawn as a circle. #HVP1 labels = data['Name1'][0], 'Robot1' sizes = [ np.mean(data[data['TYPE'] == 'HVP']['Choices1']), np.mean(data[data['TYPE'] == 'HVP']['Robot1']) ] ax3 = plt.subplot(323) ax3.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['blue', 'green'], startangle=90) ax3.axis('equal' ) # Equal aspect ratio ensures that pie is drawn as a circle. #HVP2 labels = data['Name2'][0], 'Robot2' sizes = [ np.mean(data[data['TYPE'] == 'HVP']['Choices2']), np.mean(data[data['TYPE'] == 'HVP']['Robot2']) ] ax4 = plt.subplot(324) ax4.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['red', 'green'], startangle=90) ax4.axis('equal' ) # Equal aspect ratio ensures that pie is drawn as a circle. #KVP1 labels = data['Name1'][0], 'Robot1' sizes = [ np.mean(data[data['TYPE'] == 'KVP']['Choices1']), np.mean(data[data['TYPE'] == 'KVP']['Robot1']) ] ax5 = plt.subplot(325) ax5.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['blue', 'green'], startangle=90) ax5.axis('equal' ) # Equal aspect ratio ensures that pie is drawn as a circle. #KVP2 labels = data['Name2'][0], 'Robot2' sizes = [ np.mean(data[data['TYPE'] == 'KVP']['Choices2']), np.mean(data[data['TYPE'] == 'KVP']['Robot2']) ] ax6 = plt.subplot(326) ax6.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['red', 'green'], startangle=90) ax6.axis('equal' ) # Equal aspect ratio ensures that pie is drawn as a circle. datatot = pandas.DataFrame({ 'EXPE': expeNbtot, 'TYPE': fileTypetot, 'Name1': nameS1tot, 'Name2': nameS2tot, 'Choices1': nbChoicesS1tot, 'Choices2': nbChoicesS2tot, 'Robot1': nbChoicesR1tot, 'Robot2': nbChoicesR2tot }) date = time.gmtime(None) date = str(date.tm_mday) + "-" + str( date.tm_mon) + "-" + str(date.tm_hour + 2) + "-" + str(date.tm_min) datatot.to_csv('/home/lucas/phri/lucas/fichiers_csv/data_AnDom_' + date + '.csv') plt.figure("Total") #HFOP labels = 'Sujet 1', 'Sujet 2' sizes = [ np.mean(datatot[datatot['TYPE'] == 'HFOP']['Choices1']), np.mean(datatot[datatot['TYPE'] == 'HFOP']['Choices2']) ] ax1 = plt.subplot(321) ax1.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['blue', 'red'], startangle=90) ax1.axis( 'equal') # Equal aspect ratio ensures that pie is drawn as a circle. #HFO labels = 'Sujet 1', 'Sujet 2' sizes = [ np.mean(datatot[datatot['TYPE'] == 'HFO']['Choices1']), np.mean(datatot[datatot['TYPE'] == 'HFO']['Choices2']) ] ax2 = plt.subplot(322) ax2.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['blue', 'red'], startangle=90) ax2.axis( 'equal') # Equal aspect ratio ensures that pie is drawn as a circle. #HVP1 labels = 'Sujet 1', 'Robot 1' sizes = [ np.mean(datatot[datatot['TYPE'] == 'HVP']['Choices1']), np.mean(datatot[datatot['TYPE'] == 'HVP']['Robot1']) ] ax3 = plt.subplot(323) ax3.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['blue', 'green'], startangle=90) ax3.axis( 'equal') # Equal aspect ratio ensures that pie is drawn as a circle. #HVP2 labels = 'Robot 2', 'Sujet 2' sizes = [ np.mean(datatot[datatot['TYPE'] == 'HVP']['Robot2']), np.mean(datatot[datatot['TYPE'] == 'HVP']['Choices2']) ] ax4 = plt.subplot(324) ax4.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['red', 'green'], startangle=90) ax4.axis( 'equal') # Equal aspect ratio ensures that pie is drawn as a circle. #KVP1 labels = 'Sujet 1', 'Robot 1' sizes = [ np.mean(datatot[datatot['TYPE'] == 'KVP']['Choices1']), np.mean(datatot[datatot['TYPE'] == 'KVP']['Robot1']) ] ax5 = plt.subplot(325) ax5.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['blue', 'green'], startangle=90) ax5.axis( 'equal') # Equal aspect ratio ensures that pie is drawn as a circle. #KVP2 labels = 'Robot 2', 'Sujet 2' sizes = [ np.mean(datatot[datatot['TYPE'] == 'KVP']['Robot2']), np.mean(datatot[datatot['TYPE'] == 'KVP']['Choices2']) ] ax6 = plt.subplot(326) ax6.pie(sizes, labels=labels, autopct='%1.1f%%', colors=['red', 'green'], startangle=90) ax6.axis( 'equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show()