Example #1
0
def pickfiles(name=None):
    root = Tk()
    root.withdraw()
    if name is None:
        filename = filedialog.askopenfilenames(parent=root,
                                               title="Choose DVHs ")
    else:
        filename = filedialog.askopenfilenames(parent=root, title=name)
    filename = list(filename)
    return filename
Example #2
0
def uigetfullfile(basefilename=""):
    """Act like uigetfile in matlab, returned filename can be multiple
"""
    d = GetFolderName(basefilename)
    root = tk.Tk()
    root.withdraw()
    if len(d) > 0:
        file = filedialog.askopenfilenames(initialdir=d)
    else:
        file = filedialog.askopenfilenames()
    fns = root.tk.splitlist(file)
    return fns
	def get_files(self, tk_root):
		if tk_root is not None:
			print("""If you want to pass  files directly do it by interactive_plotting(filenames = list) """)
			root = tk_root
			files = filedialog.askopenfilenames(parent=tk_root,title='Choose files')
			root.quit()
			self.filenames = files
		else:
			print("""If you want to pass  files directly do it by interactive_plotting(filenames = list) """)
			root = Tk()
			root.files = filedialog.askopenfilenames(title='Choose files')
			self.filenames = root.files
			root.withdraw()
    def __init__(self, parent=None):
        self.parent = parent
        self.parent.statusbar.showMessage("AOI Aggregation in process...")
        QWidget.__init__(self,parent)
        
        self.ui = gui.aoiUi()
        self.ui.setupUi(self)
       
        self.batch_files = filedialog.askopenfilenames(parent=root, title='Choose the file(s) you want to AOI aggregate')
        
        if len(self.batch_files) < 1:
            msgBox = QMessageBox()
            msgBox.setGeometry(400, 400, 400, 200)
            msgBox.setText("Please select one or more datasets to aggregate")
            msgBox.move(QApplication.desktop().screen().rect().center()- self.rect().center())
            msgBox.exec_() 
            
            self.close()
            return        
        
        self.columns = []
        
        self.parent.statusbar.showMessage("Checking column validity...")

        #extract columns
        for item in self.batch_files:
            self.columns.append(helpers.extract_columns(item))
 
        #check to see if all columns are equal in all the datasets
        if not helpers.are_columns_same(self.columns):
            if not helpers.columns_not_equal_message(self):
                self.close()
                return
        
        message = ""
        if self.columns != []:
            if 'GazeAOI' not in self.columns[0]:
                message += "'GAZE AOI' "
            if 'FixationAOI' not in self.columns[0]:
                message += "'FIXATION AOI'"
            
        if message != "":
            message += ": Field(s) missing from dataset - try again with appropriate data."
            reply = QMessageBox.question(self, 'Message',message, QMessageBox.Ok, QMessageBox.Ok)
            if reply == QMessageBox.Ok:
                self.parent.statusbar.showMessage("Welcome back!")
                self.close()
                return

        self.parent.ui.logOutput.append("AOI AGGREGATED:")
        print("AOI AGGREGATED:")
        
        self.AOI_aggregate('GazeAOI')
        self.AOI_aggregate('FixationAOI')
       
        #after job has been completed!
        helpers.job_complete_message(self)     
        
        self.parent.statusbar.showMessage("Welcome back!")
        self.close()
Example #5
0
    def _askfilescaller(self):
        
        """Event handler for pressing "Compile" button.
        Open tkinter AskOpenFilenames dialog.

        dialog initialdir = last accessed dir or main dir
        dialog filetypes = c source types (.c, .h, or all .*)

        if files selected, set last dir and call func to update
        sources list.

        """
        
        initialdir = self.lastdir if self.lastdir else self.main_dir
            
        sources = askopenfilenames(
                                   initialdir=initialdir, 
                                   filetypes=self.srctypes
                                   )
        
        '''Do nothing if user didn't select anything'''
        if sources:
            sources = re.findall(
                                 self.magic_filenames_ptrn, 
                                 ''.join([' ',sources, ' '])
                                 )

            self.lastdir = "/".join(sources[0].split("/")[:-1])
            self.UpdateSrcList(sources)
Example #6
0
 def add_files(self):
   errlog = ''
   try:
     open = tkinter.Tk()
     open.withdraw()
     newfiles = filedialog.askopenfilenames()
     newfiles = self.tk.splitlist(newfiles)
   except Exception:
     errlog += "{0}\n".format(traceback.format_exc())
     self.show_error(
         "Unable to add all files.\n" \
         "See Error.log for more information.",
         errlog
         )
   finally:
     filelistpaths = []
     for file in self.file_list:
       filelistpaths.append(file[1])
     newfiles = list(newfiles)
     self.delduplicates(filelistpaths, newfiles)
     
     for file in newfiles:
       self.oldname_lstbx.insert(len(self.file_list), os.path.basename(file))
       self.file_list.append([os.path.basename(file), file])
     self.update_newname()
     open.destroy()
def main():
    # Ask for CPU_usage file in text format
    root = tk.Tk()
    root.withdraw()
    Files_sel = filedialog.askopenfilenames()

    Files_l = list(Files_sel)
    Files_l.sort()

    file_name = input("Enter a file name:")

    for files in Files_l:

        tar = tarfile.open(files, mode="r")
        f = tar.getnames()

        for filename in f:
            if "meminfo" in filename:

                f = tar.extractfile(filename)
                content = f.read().splitlines()

                header = header_create(content)

                mem_parse(content, header, file_name)
def selectImages() :
    del selectedImages[:]    # Clear the list of selected images
    x = filedialog.askopenfilenames(filetypes=myfiletypes)
    if x == ('',):
        messagebox.showerror("Unable to read library location","Could not identify the location of the selected file(s). \nInstead of browsing through Windows' libraries, try selecting Desktop in the left hand pane and then open the folder that says your username. \nIdeally, you would browse through the full path of the images. E.g. C:\\Users\\[your username]\\")
    else:
        for y in x:
            selectedImages.append(y)
        # Clear the selectedPicturesFrame
        for child in selectedPicturesFrame.winfo_children():
            child.destroy()
        # Check whether we selected images
        if not selectedImages:
            Label(selectedPicturesFrame,text="None",font="none 9 italic").pack(padx=75)
        else:
            # Create the scrollbar and add it to our frame
            listboxImagesScrollbar = Scrollbar(selectedPicturesFrame,orient=VERTICAL)
            listboxImagesScrollbar.pack(side=RIGHT, fill=Y)
            # Create a listbox and add it to our user interface
            listboxImages = Listbox(selectedPicturesFrame)
            listboxImages.pack(padx=(4,3))
            # Loop through the selected images and add them to the listbox
            for selectedImg in selectedImages:  
                listboxImages.insert(END,path.basename(selectedImg))
            # Configure the scrollbar to interact with the listbox
            listboxImages.config(height=4,width=26,yscrollcommand=listboxImagesScrollbar.set)
            listboxImagesScrollbar.config(command=listboxImages.yview)
Example #9
0
def plot_navigation(paths: List[str] = None):
    """
    Plots navigation packets in the list of files. If paths is None, a file open dialog is shown
    :param paths: List of paths to plot nav data for
    :return: None
    """
    # TODO: Plot navigation from other packets if navigation packets not present.

    # Open file dialog if paths not specified
    if not paths:
        root_gui = tk.Tk()
        root_gui.withdraw()
        paths = filedialog.askopenfilenames(
            title='Select XTF files...',
            filetypes= [('eXtended Triton Files (XTF)', '.xtf')]
        )

    nav = []  # type: List[pyxtf.XTFHeaderNavigation]
    for path in paths:
        (fh, p) = xtf_read(path, types=[XTFHeaderType.navigation])
        if XTFHeaderType.navigation in p:
            nav.extend(p[XTFHeaderType.navigation])

    # Sort by time
    if nav:
        nav.sort(key=XTFHeaderNavigation.get_time)
        x = [p.RawXcoordinate for p in nav]
        y = [p.RawYcoordinate for p in nav]

        plt.plot(x, y)
        plt.show()
    else:
        warn('No navigation packets present in XTF files')
Example #10
0
    def open_mass_spectrum(self):
        try:
            self.progress.reset_bar()
            data_buffer = []
            files = filedialog.askopenfilenames(title='Select Mass '+
                                                'Spectrum File(s)')

            self.task_label.set('Opening Mass Spectra')
            for index, file in enumerate(files):
                self.progress.counter.set((float(index) /
                        len(files))*100)
                self.progress.update_progress_bar()
                self.filename = file
                mass_spec_buffer = MassSpectrum(self)
                mass_spec_buffer.open_mass_spectrum()
                data_buffer.append(mass_spec_buffer)
            self.mass_spectra = data_buffer
            self.task_label.set('Idle')
            self.progress.fill_bar()

            self.task_label.set('Plotting Mass Spectra')
            if self.mass_spectra:
                self.axes.clear()
                for index, mass_spectrum in enumerate(self.mass_spectra):
                    self.progress.counter.set((float(index) /
                        len(files))*100)
                    self.progress.update_progress_bar()
                    mass_spectrum.plot_mass_spectrum()
                finalize_plot(self)
            self.task_label.set('Idle')
            self.progress.fill_bar()
        except Exception as e:
            messagebox.showinfo('Warning','The selected files could '+
                                'not be opened.')
            self.logger.error(e)
Example #11
0
def main():
    logging_level = logging.DEBUG
    logging.Formatter.converter = time.gmtime
    log_format = '%(asctime)-15s %(levelname)s:%(message)s'
    logging.basicConfig(format=log_format, datefmt='%Y/%m/%d %H:%M:%S UTC', level=logging_level,
                        handlers=[logging.FileHandler('testparsedasbin.log'), logging.StreamHandler()])
    logging.info('_____ Started _____')

    t_step = 5 #60
    home = os.path.expanduser('~')
    start_dir = home
    status = []
    root = Tk()
    root.withdraw()  # this will hide the main window
    list_of_bin_files = filedialog.askopenfilenames(filetypes=('binary {*.bin}', 'Binary files'),
                                                    initialdir = start_dir, initialfile = '')

    for i in list_of_bin_files:
        logging.info('processing ' + i)
        status.append(pdb.parse_bin_files_to_text_files(in_filename=i, verbose_flag=True, dtm_format=True,
                                                        time_step = t_step))
        if status[-1] < 256:
            if status[-1] > 0:
                messagebox.showwarning('Warning', 'Parsing of ' + i + ' ended with warning code ' + str(status[-1])
                                       + '.')
        else:
            messagebox.showerror('Error', 'Parsing of ' + i + ' ended with error code '+ str(status[-1]) + '!')


    logging.info('______ Ended ______')
Example #12
0
def add_files(entries, color):
    path = filedialog.askopenfilenames()
    for name in path:
        if color == 'green':
            listbox_green.insert(END, name)
        else:
            listbox_red.insert(END, name)
Example #13
0
def file_chooser():
	root = Tk()
	root.files = filedialog.askopenfilenames(title='Choose files')
	if len(files) == 1:
		files = files[0]
	root.withdraw()
	return root.files
    def selectIMG(self):  # function for select target image
        self.imgName.configure(state="normal")  # entry writable
        self.imgName.delete(0, END)  # clear entry area
        self.text.delete(0.0, END)  # clear info area
        path = filedialog.askopenfilenames(
            filetypes=[  # store multiple images as array to path
                ("image files", "*.png *.gif *.bmp"),
                ("All files", "*.*"),
            ]
        )

        self.selectedIMGs = {}  # dict. store the image : size

        for img in path:
            oriSize = os.path.getsize(img)  # size of target file
            self.selectedIMGs[img] = oriSize  # add into the dictionary
            fileName = os.path.basename(img)  # get the filename
            # print(fileName)
            self.imgName.configure(state="normal")  # entry writable
            self.imgName.insert(END, fileName + ";")  # insert the image path
            self.imgName.configure(state="readonly")  # disable entry
            self.text.insert(
                END, fileName + ":" + str(round(oriSize / 1000 / 1000, 3)) + "MB\n"
            )  # display selected size

        return self.selectedIMGs
Example #15
0
def getFilenames(title, types=[], initialdir=None):
    root = Tk()
    root.withdraw()
    filenames = filedialog.askopenfilenames(title=title, filetypes=types,
                                            initialdir=initialdir)
    root.destroy()
    return root.tk.splitlist(filenames)
Example #16
0
    def load_new_tables(self):
        '''Opens a file chooser dialog so that the user can choose table files
           to load. Loads these into dicts.'''

        file_opts = {"defaultextension": ".csv",
                     "title": "Choose table file(s)",
                     }
        filenames = filedialog.askopenfilenames(**file_opts)
        for f in filenames:
            table_name = f[f.rfind('/')+1:f.rfind('.csv')]
            try:
                self.tables[table_name] = load_table(f)
            except TableFormatError as err:
                mbox.showwarning("Open file",
                                 "Bad formatting: {}".format(err.err_msg))
                return
            except csvError:
                mbox.showwarning("Open file",
                                 "Cannot open file: Bad CSV input.")
                return
            except FileNotFoundError:
                mbox.showwarning("Open file",
                                 "Cannot open file: File not found.")
                return
            # Update the options in self.table_menu.
            new_comm = tk._setit(self.chosen_table, table_name)
            self.table_menu['menu'].add_command(label=table_name,
                                                command=new_comm)
Example #17
0
 def add_files(self):
     options = {}
     config = self.parent.settings_frame.config
     options['defaultextension'] = config["File"]["Extension"]
     if options['defaultextension'] == ".txt":
         options['filetypes'] = [('Text files', '.txt'), ('XML files', '.xml'),
                                 ('HTML files', '.html')]
     if options['defaultextension'] == ".xml":
         options['filetypes'] = [('XML files', '.xml'), ('Text files', '.txt'),
                                 ('HTML files', '.html')]
     if options['defaultextension'] == ".html":
         options['filetypes'] = [('HTML files', '.html'),
                                 ('Text files', '.txt'),
                                 ('XML files', '.xml')]
     default_dir = config["File"]["InputDir"].strip()
     if os.path.exists(default_dir):
         options['initialdir'] = default_dir
     else:
         options['initialdir'] = ""
     options['initialfile'] = ''
     options['parent'] = self.setup_frame
     options['title'] = 'Open corpus file(s)'
     files_str = filedialog.askopenfilenames(**options)
     for f in self.parent.root.splitlist(files_str):
         self.files.append(f)
         self.listbox.insert("end", os.path.basename(f))
Example #18
0
    def abrir_pt1(self):

        self.status.configure(text = 'Abrindo arquivos...')
        self.arquivos = sorted(filedialog.askopenfilenames(title='Abrir',
                        filetypes=[('SAC','*.sac')]))

        if len(self.arquivos) > 0:

            try:

                for i in self.arquivos:

                    self.sts.append(read(i))

               # for i in self.sts:

                #    print(i[0].stats.station)'''

                self.abrir_pt2()

            except:

                messagebox.showerror("Sismologica","Erro na leitura do arquivo.")
                self.status.configure(text = '')
                del self.sts[:]
                self.arquivo = None
Example #19
0
 def do_share(self):
     """Share songs."""
     paths = filedialog.askopenfilenames()
     if isinstance(paths, str):  # http://bugs.python.org/issue5712
         paths = self.master.tk.splitlist(paths)
     logging.debug("paths: {}".format(paths))
     for path in paths:
         self.user.recommend(path)
     self.update()
def showopen():
    file_names = filedialog.askopenfilenames(title = "select your favourite song",filetypes=[("mp4 file","*.mp4"),("mp3 file","*.mp3")])
    #askopenfilenames is basically a method of class filedialog present in tkinter module
    print(type(file_names))
    print((file_names))
    str = ""
    for x in file_names:
        str+=x + "\n"
    lbl.configure(text = str)
Example #21
0
    def OpenFileCommand(self):

        InputfilesList = filedialog.askopenfilenames(title="Select the source input file(s)", filetypes=[("All files",".*")])
        InputfilesList =  self.root.tk.splitlist(InputfilesList)
        for i in range ((len(InputfilesList))):
            if InputfilesList[i][-3:].lower() in ('mp4','wav','avi','mov','wmv'):
                self.queue_app.put(['setFileNameLIst', [InputfilesList]])
            else:
                messagebox.showinfo('error','choose a mp4, AVI, mov file' )
Example #22
0
def get_filenames_UI(UIdir=None, UIcaption='', UIfilters=''):
    """
    Custom function that is equivalent to Matlab's uigetfile command. Returns filename as a string.

    filenamestring = GetFile(UIdir=None,UIcaption='',UIfilters='')
    """
    withdraw_tkinter()
    filenames = askopenfilenames()
    return filenames
        def Load_inputs_callback():
            Load_filename = askopenfilenames()
            List.delete(0,"end") #Should a load command delete the current set? With this in it will.
            print(Load_filename[0])

            with open(Load_filename[0]) as text_file:
                print (text_file)
                for i, l in enumerate(text_file):
                    List.insert("end", l) 
Example #24
0
 def load_file(self):
     if self.isAuth == 1:
         fname = askopenfilenames()
         size = len(fname)
         for x in range(size):
             piece = splitFiles(fname[x],key)
             Encrypted_List.append((fname[x].rsplit('/', 1)[1]))
             File_List.append((fname[x],piece))
         self.init_EncryptedList()
Example #25
0
 def get_input_files(self):
     """Pop up the 'open file' dialog, assign whatever's picked to the input file entry box, and set an attribute with an iterable of the file selectors."""
     options = {
         "title": "Select file",
     }
     selectors = tkfd.askopenfilenames(**options)
     self.input_selectors = selectors
     self.infile.delete(0, tk.END)
     self.infile.insert(0, selectors)
     return None
 def make_widgets(self):
     MLabel(self, text='文件对话框演示')
     self.label = MLabel(self, text='等待测试...')
     MButton(self, text='打开目录', command=lambda: self.print_result(filedialog.askdirectory()))
     MButton(self, text='打开文件', command=lambda: self.print_result(filedialog.askopenfile()))
     MButton(self, text='选择文件名', command=lambda: self.print_result(filedialog.askopenfilename()))
     MButton(self, text='选择多个文件名', command=lambda: self.print_result(filedialog.askopenfilenames()))
     MButton(self, text='打开多个文件', command=lambda: self.print_result(filedialog.askopenfiles()))
     MButton(self, text='保存为...', command=lambda: self.print_result(filedialog.asksaveasfile()))
     MButton(self, text='保存为文件名...', command=lambda: self.print_result(filedialog.asksaveasfilename()))
Example #27
0
 def add(self):
     file = tk.askopenfilenames(initialdir='C:/Users/babbu/Downloads')  
     songsTuple = root.splitlist(file)   #turn user's opened filenames into tuple
     songsList = list(songsTuple)        #convert to list
     #Add the full filename of songto playlist list, and a shortened version to the listBox
     for song in songsList:              
         playlist.append(song);          
         tempArray = song.split('/')     
         songShort = tempArray[len(tempArray)-1]
         self.playlistbox.insert(END, songShort)
Example #28
0
def getFilenames(title, types=[], initialdir=None):
    try:
        root = Tk()
        root.withdraw()
        filenames = filedialog.askopenfilenames(title=title, filetypes=types,
                                                initialdir=initialdir)
        root.destroy()
        return root.tk.splitlist(filenames)
    except OSError:
        print("No files selected!")
Example #29
0
    def add_file(self):
        new_files = askopenfilenames(filetypes=[("Wave", "*.wav")])
        if new_files:
            for new_file in new_files:
                try:
                    self.mp3_engine.add_audio_file(new_file)
                except RuntimeError:
                    showerror("Import Error", new_file + " is already in your queue.")

        self.flush_tree()
Example #30
0
def doCopy():
    
    global entryWidget
    global statusWidget
    
    srcPath = "c:\\temp\\src"
    destPath = "c:\\temp\\dest"
    readMeFilePath = "c:\\temp\\dest\\ReadMe.txt"
    
    #prompt for file selection
    options = {}
    options['title'] = "Select APEX Files"
    options['initialdir'] = srcPath
    options['filetypes'] = [("txt files",".txt")]
    selectedFiles = askopenfilenames(**options)
    
    #split selected files string into a list
    fileList = root.tk.splitlist(selectedFiles)
    
    
    #delete .apex existing files
    deleteFiles = entryDelete.get().strip()
    if deleteFiles == "yes":
        for filename in os.listdir(destPath):
            deleteFile = os.path.join(destPath, filename)
            if deleteFile.endswith(".txt"):
                os.remove(deleteFile)
                statusWidget.insert(END, "\n" + "  Deleted File: " + filename)
                root.update_idletasks()
    
    #update status
    statusWidget.insert(END, "\n\n" + "Selected Files")
    for file in fileList:
        statusWidget.insert(END, "\n" + str(file))
        root.update_idletasks()
    
    #copy the files
    with open(readMeFilePath, mode = "a") as readMeFile:
        now = datetime.datetime.now()
        readMeFile.write("\n\n" + os.environ.get("USERNAME", "Butterfield") + " - " + now.strftime("%m-%d-%Y %H:%M %p"))
        readMeFile.write("\n" + entryWidget.get().strip())
        readMeFile.write("\n" + "Installed the following packages:")
        
        for copyFile in fileList:
            statusWidget.insert(END, "\n\n" + "Copying File: " + copyFile)
            statusWidget.yview(MOVETO, 1.0)
            root.update_idletasks()
            shutil.copy(copyFile, destPath)
            readMeFile.write("\n   [" + os.path.split(copyFile)[1] + "]")
            #update status
            statusWidget.insert(END, " - DONE!")
            root.update_idletasks()
            
        statusWidget.insert(END, "\n\n" + "COMPLETE!")        
        statusWidget.yview(MOVETO, 1.0)    
Example #31
0
def clicked():

    plot.cla()
    plot2.cla()

    file = filedialog.askopenfilenames()
    input = text.get("1.0", tkinter.END)

    # se l'utente non specifica il gap, ne viene settato uno di default
    if text.compare("end-1c", "==", "1.0") or isinstance(input,
                                                         str) or input <= 0:
        gap_value = def_gap
    else:
        gap_value = float(input)

    selection = v.get()
    instanceProblem = setting_data_problem(file)

    # calcolo della soluzione ottima intera
    integer_optimal_solution = solve_problem_binario(instanceProblem)
    integer_optimal_solution = float(integer_optimal_solution)

    canvas = FigureCanvasTkAgg(figure, window)
    canvas.get_tk_widget().grid(row=10, column=3)

    canvas2 = FigureCanvasTkAgg(figure2, window)
    canvas2.get_tk_widget().grid(row=10, column=4)

    if selection == 1:
        # Gomory cuts interi
        percent_limit = gap_value
        iteration_manager = GomoryIterationManager(float(0), False,
                                                   percent_limit)
        solve_problem_intero(instanceProblem, iteration_manager)
    elif selection == 2:
        # Gomory cuts frazionari
        percent_limit = gap_value
        iteration_manager = GomoryIterationManager(float(0), False,
                                                   percent_limit)
        solve_problem_frazionario(instanceProblem, iteration_manager)
    elif selection == 3:
        # Gomory cuts interi multipli
        percent_limit = gap_value
        iteration_manager = GomoryIterationManager(float(0), False,
                                                   percent_limit)
        solve_problem_multiple_interi(instanceProblem, iteration_manager)
    elif selection == 4:
        # Gomory cuts frazionari multipli
        percent_limit = gap_value
        iteration_manager = GomoryIterationManager(float(0), False,
                                                   percent_limit)
        solve_problem_multiple_frazionario(instanceProblem, iteration_manager)

    x1 = [0, instanceProblem.num_try]
    y1 = [integer_optimal_solution, integer_optimal_solution]
    plot.plot(x1, y1)

    x2 = [0] * instanceProblem.num_try
    y2 = [0] * instanceProblem.num_try
    for i in range(instanceProblem.num_try):
        x2[i] = i
        y2[i] = instanceProblem.optimal_solution[i]

    plot.plot(x2, y2, color="lightblue", marker=".", linestyle="")
    plot2.plot(x2, y2, color="lightblue", marker=".", linestyle="")

    final_lbl0 = Label(window, text="     ")
    final_lbl0.grid(column=3, row=10)
    final_lbl = Label(window,
                      text=" Numero di iterazioni : " +
                      str(round(instanceProblem.num_try, 6)))
    final_lbl.grid(column=3, row=13)
    final_lbl01 = Label(window, text="     ")
    final_lbl01.grid(column=3, row=14)
    final_lbl2 = Label(window,
                       text=" Valore iniziale : " +
                       str(round(instanceProblem.optimal_solution[0], 6)))
    final_lbl2.grid(column=3, row=15)
    final_lbl3 = Label(
        window,
        text=" Valore finale : " +
        str(round(instanceProblem.optimal_solution[instanceProblem.num_try],
                  6)))
    final_lbl3.grid(column=3, row=16)
    incremento = instanceProblem.optimal_solution[
        instanceProblem.num_try] - instanceProblem.optimal_solution[0]
    final_lbl4 = Label(
        window,
        text=" Incremento :  " + str(round(incremento, 6)) + "      ( " +
        str(round(100 * incremento / instanceProblem.optimal_solution[0], 6)) +
        " % )")
    final_lbl4.grid(column=4, row=15)
    final_lbl5 = Label(
        window,
        text=" Distanza dall'ottimo intero :  " + str(
            round(
                integer_optimal_solution -
                instanceProblem.optimal_solution[instanceProblem.num_try], 6)))
    final_lbl5.grid(column=4, row=16)
from tkinter import filedialog

#%% TKinter GUI for selecting files.
root = tk.Tk()
root.overrideredirect(True)
root.geometry('0x0+0+0')
root.focus_force()

initial_folder = "C:/"  # Change the default directory here.
FT = [("All files", "*.*"), ("Abf files", "*.abf"), ("Excel files", "*.xlsx"),
      ("CSV files", "*.csv")]

ttl = 'Select Files'

file_paths = filedialog.askopenfilenames(parent=root,
                                         title=ttl,
                                         filetypes=FT,
                                         initialdir=initial_folder)

root.withdraw()

#%% Loop for each selected file

for file_path in file_paths:

    split = os.path.split(file_path)
    file_extension = os.path.splitext(split[1])[1][1:]

    file_name = os.path.basename(os.path.normpath(file_path))

    # Extracting the signals according to type of files
    if file_extension == 'abf':
Example #33
0
		# if "data" in cName and "python" in cName:
			# pyColumn = i
			# print("data types in python in column :", i)
		if cName==hh:
			# print("header #", i)
			# print(cName)
			# print("found it!")
			return i
		if i == len(Canheader)-1:
			print("no column in canvas was found associated with this assignment!")
			col = int(input("Enter the column to edit in CANVAS, refer to CanvasColumn.xlsx file in TA drive: "))
			return col+3 
	
root = tkinter.Tk()
root.withdraw()
filez = filedialog.askopenfilenames(parent=root,title='SELECT ALL HACKERANK FILES')
fileList = list(filez)
	
for i in range(0, len(fileList)):
	with open(fileList[i]) as csvDataFile:
		csvReader = csv.reader(csvDataFile)
		Hr = list(csv.reader(csvDataFile))
	
	head, HRtail = os.path.split(fileList[i])
	print("You have successfully imported HR file ", HRtail)	
	numrows1 = len(Hr)          
	numcols1 = len(Hr[0])
	col = getCol(HRtail)
	print("this is the respective column : ", col)
	if col < 46:
		points = 100
Example #34
0
def getDataBaseToBeUsed():
    root = tk.Tk()
    root.withdraw(
    )  # we don't want a full GUI, so keep the root window from appearing
    paths = askopenfilenames(title='Choose the databases')
    return paths
Example #35
0
 def btn_select_clicked(self):
     self.path.insert(0, filedialog.askopenfilenames())
     self.btn_upload.config(state="normal")
    def findPeakPos(self):

        file_path = filedialog.askopenfilenames()

        folder = file_path[0].split('/')

        path = ''
        for i in range(0, len(folder) - 1):
            path = path + folder[i] + "/"
        path = path + 'Resolution.txt'

        try:
            with open(path, 'r') as f:
                for line in f.readlines():
                    category, value = line.strip().split(';')
                self.deltaT = float(value)
        except:
            self.deltaT = FileHandle.getResolution()

        self.LoadCsvBar.setMaximum(len(file_path))
        self.show()
        diff_peaks = []
        pos_array = []
        stringdata = ""
        for numb, i in enumerate(file_path):
            val = []
            self.LoadCsvBar.setValue(numb + 1)
            QtGui.QGuiApplication.processEvents()
            try:
                with open(i) as csv_file:
                    reader = csv.reader(csv_file, delimiter=';')

                    for row in reader:
                        if len(row) == 1:
                            val.append(float(row[0]))
                        else:
                            val.append(float(row[1]))
            except:
                break
                self.close()
                return

            valarray = np.asarray(val)

            maxval = np.max(valarray)

            peaks, _ = find_peaks(valarray,
                                  height=(maxval * 0.8, maxval),
                                  distance=19 / self.deltaT)

            diff_peaks.append(peaks * self.deltaT)

            pos_array = np.asarray(list(peaks * self.deltaT))

            for i in pos_array:
                stringdata = stringdata + str(i) + ";"

            stringdata = stringdata + "\n"

        diff_peaks = list(diff_peaks)

        diff = []
        for i in diff_peaks:
            diff = np.append(diff, i[1:-1] - i[0:-2])

        FileHandle.SaveData(time=range(len(diff)), data=diff)

        try:
            savefile = filedialog.asksaveasfile(mode='w',
                                                defaultextension=".csv").name

            with open(savefile, "w+") as f:
                f.write(stringdata)
                #for val in stringdata:
                #  print(val)
                # f.write(val)
        except:
            return

        self.close()
Example #37
0
def select_file():
    global log_file
    log_file = filedialog.askopenfilenames(title="请选择剧本文件", filetypes=[("Text", "*.txt"), ("All Files", "*")])[0]
from paths import master_path
from functions_misc import tk_killwindow
from tkinter.filedialog import askopenfilenames
import numpy as np
from functions_gratings import calculate_dsi_osi, project_angles
import matplotlib.pyplot as plt


tk_killwindow()

# get the files
filenames = askopenfilenames(initialdir=master_path)

# for all the filenames
for files in filenames:
    # load the data
    contents = np.load(files, allow_pickle=True)
    data = contents['data'].item()
    # check if there is a DG field, otherwise skip it
    if 'DG' not in data:
        continue
    # calculate DSI, OSI for each ROI
    data = data['DG']
    # get the number of ROIs
    roi_number = data['data'].shape[0]
    # calculate the trial average
    trial_average = np.nanmean(data['data'], axis=2)
    # get the angle exponentials
    angle_exponentials = project_angles(np.unique(data['trial_info'][:, 1]).astype(np.int32))
    # allocate memory for the indexes
    dsi_osi_list = [calculate_dsi_osi(trial_average[roi, :, :], angle_exponentials) for roi in np.arange(roi_number)]
Example #39
0
from tkinter import filedialog as fd
from tkinter import messagebox
import os
import tarfile

# import sys, and then the gdal_merge from the local file location
import sys
sys.path.append(r"C:\Program Files\QGIS 2.18\bin")
import gdal_merge

# setup TK window and hide so only dialogs are visible
root = Tk()
root.withdraw()

# user input of landsat tar.gz filenames to be extracted, abort if no files selected
fileraw = fd.askopenfilenames(initialdir = "/", title = "Select Landsat tar.gz files")
if len(fileraw) == 0:
    messagebox.showwarning("File Selection", "No files selected")
    quit()

# user input of output file location, abort if no folder selected
outlocation = fd.askdirectory(title="Please select an output folder")
if len(outlocation) == 0:
    messagebox.showwarning("Output location", "No output folder selected")
    quit()

# convert tuple of files into list, and loop through each tar file, performing extraction and merge
filelist = list(fileraw)
for infile in filelist:

    # if file is not a tar.gz file, skip
Example #40
0
from tkinter import filedialog
from os import path

empty_set = set()
empty_list = list()
aggr_list = list()

cnt = 0
temp = 0

sheet_name_array = []
hoge = []

select_file = tk.Tk()
select_file.withdraw()
full_path = filedialog.askopenfilenames()

for f in full_path:
    drive, tail = path.split(f)
    root, ext = path.splitext(f)
    wb = xlrd.open_workbook(f)
    sheet_name_array = wb.sheet_names()
    sheet = wb.sheet_by_name('解析結果')
    for row in range(3, sheet.nrows):
        hoge = str(sheet.cell(row, 3).value).split('\n')
        for hogehoge in hoge:
            empty_set.add(hogehoge)

empty_set.remove('')
empty_set.remove('42')
Example #41
0
import os
import openpyxl
import tkinter as tk
import tkinter.filedialog as tkdialog
import tkinter.messagebox as tkmbox
import module_spfi_csv_cov_pd_rev01 as csvconv

root = tk.Tk()  #ウィンドウオブジェクトを作成
root.withdraw()  #ウィンドウを表示しない設定
fTyp = [("", "csv")]  #ファイルタイプ
iDir = os.path.abspath(os.path.dirname(__file__))  #ファイルのdir名からdirパスを取得
tkmbox.showinfo('csv変換', '変換するCSVファイルを選択してください(複数可)')

files = tkdialog.askopenfilenames(filetypes=fTyp,
                                  initialdir=iDir)  #ファイルのフルパスのタプルを作成

for file in files:
    csvconv.spfi_csv_conv(file)
Example #42
0
from PIL import Image
from tkinter import Tk, filedialog
root = Tk()
root.withdraw()
alpha = Image.open(
    filedialog.askopenfilename(filetypes=[("Alpha Image",
                                           " *.png;*.bmp;*.jpg")]))
alpha = alpha.getchannel("A")
inputs = filedialog.askopenfilenames(filetypes=[("Input Images",
                                                 " *.png;*.bmp;*.jpg")])
for image in inputs:
    im = Image.open(image)
    im = Image.merge(
        "RGBA",
        (im.getchannel("R"), im.getchannel("G"), im.getchannel("B"), alpha))
    im.save(image)
quit()
    def MakeAvg(self, printer):

        file_path = filedialog.askopenfilenames()

        folder = file_path[0].split('/')

        path = ''
        for i in range(0, len(folder) - 1):
            path = path + folder[i] + "/"
        path = path + 'Resolution.txt'

        try:
            with open(path, 'r') as f:
                for line in f.readlines():
                    category, value = line.strip().split(';')
                self.deltaT = float(value)
        except:
            self.deltaT = FileHandle.getResolution()

        cutval = []

        self.LoadCsvBar.setMaximum(len(file_path))
        self.show()
        for numb, i in enumerate(file_path):
            val = []
            self.LoadCsvBar.setValue(numb + 1)
            QtGui.QGuiApplication.processEvents()
            try:
                with open(i) as csv_file:
                    reader = csv.reader(csv_file, delimiter=';')

                    for row in reader:
                        if len(row) == 1:
                            val.append(float(row[0]))
                        else:
                            val.append(float(row[1]))
            except:

                break
                self.close()
                return

            valarray = np.asarray(val)

            maxval = np.max(valarray)

            peaks, _ = find_peaks(valarray,
                                  height=(maxval * 0.6, maxval),
                                  distance=19 / self.deltaT)

            distance = peaks[1:-1] - peaks[0:-1 - 1]

            try:
                if np.min(distance) * self.deltaT < 18 or np.max(
                        distance) * self.deltaT > 25:

                    continue
            except:
                continue

            if (min(peaks) < 20):

                continue
            print(i)
            valarray = valarray[peaks[0] + 700:-1]

            cutval.append(valarray)
        #############################################
        #self.close()
        plt.subplot(2, 1, 1)
        plt.grid(which='both', axis='both')
        print("/////////////////")
        length = []

        for i in cutval:
            length.append(len(i))
        try:
            minlength = np.min(length)
        except:
            self.close()
            return
        Timeaxis = np.arange(0, minlength, 1) * self.deltaT

        timemask = Timeaxis < 210
        Timeaxis = Timeaxis[timemask]
        avg = np.zeros(len(Timeaxis))

        for number, i in enumerate(cutval):
            cutval[number] = i[0:minlength]
            cutval[number] = cutval[number][timemask]
            avg = avg + cutval[number]
            plt.plot(Timeaxis, cutval[number])

        avg = np.true_divide(avg, len(cutval))
        print(len(cutval))
        plt.xlabel(r"Zeit t [ps]")
        plt.ylabel(r"V$_{\rm{TIA}}$")
        ###################################################################################

        plt.subplot(2, 1, 2)
        plt.plot(Timeaxis, avg, label='Mittelwert')
        plt.grid(which='both', axis='both')
        plt.xlabel(r"Zeit t [ps]")
        plt.ylabel(r"V$_{\rm{TIA}}$")
        plt.xlabel(r"Zeit t [ps]")
        plt.legend()
        self.close()

        FileHandle.SaveData(Timeaxis, avg)

        plt.show()
Example #44
0
def main(argv):
	config = read_parser(argv, Inputs, InputsOpt_Defaults)
	from Main_Analysis import invoke_signal
	
	if config['mode'] == 'avg_spectrum':
		n_avg = config['n_avg']
		magX_list =  []
		for i in range(n_avg):			
			dict_int = invoke_signal(config)
			x = dict_int['signal']
			t = dict_int['time']
			f = dict_int['freq']
			magX = dict_int['mag_fft']
			filename = dict_int['filename']
			
			
			if i == 0:
				magX_avg = np.zeros(len(magX))
			magX_avg = magX_avg + magX
		magX_avg = magX_avg / float(n_avg)
		
		fig, ax = plt.subplots()
		ax.plot(f, magX_avg)
		ax.set_xlabel('Frequency [Hz]')
		plt.show()
		
		
		if config['save'] == 'ON':
			mydict = {}
			mydict['freq_array'] = f
			mydict['avg_spectrum'] = magX_avg		
			
			if config['name'] == 'auto':
				import datetime
				stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
			else:
				stamp = config['name']
			save_pickle('avg_spectrum_' + config['channel'] + stamp + '.pkl', mydict)
		else:
			print('no save')
		
		# plt.plot(f/1000., magX_avg)
		# plt.xlabel('Frequenz [kHz]')
		# params = {'mathtext.default': 'regular' }          
		# plt.rcParams.update(params)
		# plt.ylabel('Amplitude [mV]')
		# plt.show()
		

	elif config['mode'] == 'plot_spectrum':
		
		magX_avg_list = []
		f_list = []
		
		root = Tk()
		root.withdraw()
		root.update()
		Filenames = filedialog.askopenfilenames()
		root.destroy()	
		
		for filename in Filenames:
			print(os.path.basename(filename))
			mydict = read_pickle(filename)		
			f_list.append(mydict['freq_array'])
			magX_avg_list.append(mydict['avg_spectrum'])
			
		

		channel = 'AE_1'
		element = 'Mag-FFT'
		fig, ax = plt.subplots(nrows=3, ncols=1, sharex=True, sharey=True)
		# ax[].set_title(channel + ' ' + element + '\n' + os.path.basename(filename), fontsize=10)
		
		ax[0].set_title('BMB am Punkt D', fontsize=10, fontweight='bold')
		ax[1].set_title('Drahtbuerste am Punkt F', fontsize=10, fontweight='bold')
		ax[2].set_title('Kugelfall Maximale Hoehe', fontsize=10, fontweight='bold')
		ax[0].title.set_position([0.5, 1.0])
		ax[1].title.set_position([0.5, 0.8])
		ax[2].title.set_position([0.5, 0.8])

		
		
		ax[0].plot(f_list[0]/1000., magX_avg_list[0], 'r')
		ax[1].plot(f_list[1]/1000., magX_avg_list[1], 'r')
		ax[2].plot(f_list[2]/1000., magX_avg_list[2], 'r')
		
	
		ax[2].set_xlabel('Frequenz kHz')
		ax[0].ticklabel_format(axis='y', style='sci', scilimits=(-1, 1))
		ax[1].ticklabel_format(axis='y', style='sci', scilimits=(-1, 1))
		ax[2].ticklabel_format(axis='y', style='sci', scilimits=(-1, 1))
		params = {'mathtext.default': 'regular' }          
		plt.rcParams.update(params)
		ax[0].set_ylabel('Amplitude (m$V_{in}$)')
		ax[1].set_ylabel('Amplitude (m$V_{in}$)')
		ax[2].set_ylabel('Amplitude (m$V_{in}$)')
		
		plt.show()
		
	elif config['mode'] == 'plot_avg_spectrum':
		
		magX_avg_list = []
		f_list = []
		
		root = Tk()
		root.withdraw()
		root.update()
		Filenames = filedialog.askopenfilenames()
		root.destroy()	
		
		for filename in Filenames:
			print(os.path.basename(filename))
			mydict = read_pickle(filename)		
			f_list.append(mydict['freq_array'])
			magX_avg_list.append(mydict['avg_spectrum'])
			
		

		channel = config['channel']
		element = 'Mag-FFT'
		fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True)
		# ax[].set_title(channel + ' ' + element + '\n' + os.path.basename(filename), fontsize=10)
		
		# ax.set_title(config['channel'] + ' FFT-Average WB-Source at F', fontsize=10, fontweight='bold')
		# title = config['channel'] + ' FFT-Mittelwert Hsu-Nielsen-Bursts'
		title = config['channel'] + ' FFT-Mittelwert'
		title = title.replace('_', '-')
		
		
		ax[0].set_title('Mit Lack', fontsize=12)
		ax[1].set_title('Ohne Lack', fontsize=12)
		# ax.ticklabel_format(axis='y', style='sci', scilimits=(-1, 1))
		
		
		ax[0].plot(np.array(f_list[0])/1000., magX_avg_list[0]*1000., 'r')
		ax[1].plot(np.array(f_list[1])/1000., magX_avg_list[1]*1000., 'darkred')

		
	
		# ax.set_xlabel('Frequency (kHz)')
		ax[1].set_xlabel('Frequenz [kHz]', fontsize=12)

		params = {'mathtext.default': 'regular' }          
		plt.rcParams.update(params)
		ax[1].set_ylabel('Amplitude [mV]', fontsize=12)
		ax[0].set_ylabel('Amplitude [mV]', fontsize=12)
		ax[0].tick_params(axis='both', labelsize=11)
		ax[1].tick_params(axis='both', labelsize=11)

		plt.tight_layout()
		plt.show()
		
		
	
	else:
		print('unknown mode')
		
		
		
	return
    def LoadPLot(self):

        file_path = filedialog.askopenfilenames()
        try:
            folder = file_path[0].split('/')
        except:
            return

        path = ''
        for i in range(0, len(folder) - 1):
            path = path + folder[i] + "/"
        path = path + 'Resolution.txt'

        try:
            with open(path, 'r') as f:
                for line in f.readlines():
                    category, value = line.strip().split(';')
                self.deltaT = float(value)
                print(self.deltaT)
        except:
            self.deltaT = FileHandle.getResolution()
            print(self.deltaT)
        self.LoadCsvBar.setMaximum(len(file_path))
        self.show()

        try:
            for numb, i in enumerate(file_path):
                avg = []
                Timearray = []
                oneax = True
                self.LoadCsvBar.setValue(numb + 1)
                QtGui.QGuiApplication.processEvents()
                with open(i) as csv_file:
                    reader = csv.reader(csv_file, delimiter=';')

                    for row in reader:
                        if len(row) == 2:
                            Timearray.append(float(row[0]))
                            avg.append(float(row[1]))
                            oneax = False
                        else:
                            avg.append(float(row[0]))

                avgarray = np.asarray(avg)

                if oneax:
                    Timearray = np.arange(0, len(avgarray), 1) * self.deltaT

                plt.plot(Timearray, avgarray)
                plt.xlabel(r"Zeit t [ps]")
                plt.ylabel(r"V$_{\rm{TIA}}$")
                del Timearray
                del avgarray
                del avg
                gc.collect()

        except:
            self.close()
            return

        self.close()
        plt.grid()
        plt.show()

        gc.collect()
        return
Example #46
0
    def plotSelectedGraph(self):
        selectedFiles = askopenfilenames()
        x = []
        y = []
        x2 = []
        y2 = []
        x3 = []
        y3 = []
        x4 = []
        y4 = []
        x5 = []
        y5 = []
        x6 = []
        y6 = []
        xall = []
        yall = []
        if len(selectedFiles) == 1:
            with open(selectedFiles[0]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        x.append(int(line.split()[0])/ 1000.0)
                        y.append(float(line.split()[1]))
        elif len(selectedFiles) == 2:
            with open(selectedFiles[0]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        x.append(int(line.split()[0])/ 1000.0)
                        y.append(float(line.split()[1]))
            with open(selectedFiles[1]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        x2.append(int(line.split()[0])/ 1000.0)
                        y2.append(float(line.split()[1]))
        elif len(selectedFiles) == 3:
            with open(selectedFiles[0]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        x.append(int(line.split()[0])/ 1000.0)
                        y.append(float(line.split()[1]))
            with open(selectedFiles[1]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        x2.append(int(line.split()[0])/ 1000.0)
                        y2.append(float(line.split()[1]))
            with open(selectedFiles[2]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        x3.append(int(line.split()[0])/ 1000.0)
                        y3.append(float(line.split()[1]))
                        
        
        elif len(selectedFiles) == 6:
           with open(selectedFiles[0]) as f:
               for i, line in enumerate(f):
                   if i > 8:
                       x.append(int(line.split()[0])/ 1000.0)
                       y.append(float(line.split()[1]))
           with open(selectedFiles[1]) as f:
               for i, line in enumerate(f):
                   if i > 8:
                       x4.append(int(line.split()[0])/ 1000.0)
                       y4.append(float(line.split()[1]))
           
           with open(selectedFiles[2]) as f:
               for i, line in enumerate(f):
                   if i > 8:
                       x2.append(int(line.split()[0])/ 1000.0)
                       y2.append(float(line.split()[1]))
                       
           with open(selectedFiles[3]) as f:
               for i, line in enumerate(f):
                   if i > 8:
                       x5.append(int(line.split()[0])/ 1000.0)
                       y5.append(float(line.split()[1]))
           with open(selectedFiles[4]) as f:
               for i, line in enumerate(f):
                   if i > 8:
                       x3.append(int(line.split()[0])/ 1000.0)
                       y3.append(float(line.split()[1]))
                       
           with open(selectedFiles[5]) as f:
               for i, line in enumerate(f):
                   if i > 8:
                       x6.append(int(line.split()[0])/ 1000.0)
                       y6.append(float(line.split()[1]))
        # 4 files selected
        else:
            with open(selectedFiles[0]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        x.append(int(line.split()[0])/ 1000.0)
                        y.append(float(line.split()[1]))
            with open(selectedFiles[1]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        x2.append(int(line.split()[0])/ 1000.0)
                        y2.append(float(line.split()[1]))
            with open(selectedFiles[2]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        x3.append(int(line.split()[0])/ 1000.0)
                        y3.append(float(line.split()[1]))

            with open(selectedFiles[3]) as f:
                for i, line in enumerate(f):
                    if i > 8:
                        xall.append(int(line.split()[0]) / 1000.0)
                        yall.append(float(line.split()[1]))          


        plt.plot(x, y, 'r.-')
        plt.plot(x2, y2, 'y.-')
        plt.plot(x3, y3, 'g.-')
        plt.plot(x4, y4, 'y.-')
        plt.plot(x5, y5, 'kx')
        plt.plot(x6, y6, 'cx')
#        plt.plot(xall,yall, 'c')
#        plt.plot(xall,yall, linestyle = '-')
        #plt.ylim(0, 5000)
        plt.title('Voltage Sweep Over Time')
        plt.xlabel('Time(ms)')
        plt.ylabel('Voltage(mV)')
        plt.show()
Example #47
0
 def get_img_paths(self):
     self.img_paths = list(
         filedialog.askopenfilenames(initialdir="C:/", title="Images"))
     self.img_paths_field.delete(0, len(self.img_paths_field.get()))
     self.img_paths_field.insert(0, str(self.img_paths))
Example #48
0
# plot_trial_feature.py
from tkinter.filedialog import askopenfilenames
import matplotlib.pyplot as plt
from scipy import signal
import numpy as np
import pandas as pd
import sys,os
import re

files = askopenfilenames()
print(files)

primitives = ['x-corr','y-corr']
derivatives = ['x-vel','y-vel','speed']

for file in files:
    df = pd.read_csv(file)
    FPS = float(input('Enter FPS for this feature timeseries: '))
    fig, axes = plt.subplots(len(primitives)+len(derivatives)+1,1,squeeze=False,sharex=True,figsize=(16,10))
        
    b,a = signal.butter(5,0.2)
    for i,feature in enumerate(primitives):
    
        # convert mm to m
        if ( ( feature == 'x-corr') | ( feature == 'y-corr' ) ):
            df[feature] = df[feature] / 1000   
            unit = 'm'
            df['{}-filtered'.format(feature)] = signal.filtfilt(b,a,df[feature].fillna(value=0.0).to_numpy())
            axes[i,0].plot(df['time'],df[feature],color='dimgray',label='original')
            axes[i,0].plot(df['time'],df['{}-filtered'.format(feature)],color='k',linestyle='--',label='filtered')
            axes[i,0].set_ylabel('{} ({})'.format(feature,unit))
Example #49
0
 def add_files(self) -> None:
     self.listbox.insert('end',
                         *map(try_relpath, tkfiledialog.askopenfilenames()))
Example #50
0
 def filename_multi(self):
     """ Get multiple existing file locations """
     logger.debug("Popping Filename browser")
     return filedialog.askopenfilenames(**self.kwargs)
 def import_file():
     filelist = tkfd.askopenfilenames(**self.file_opt)
     global files
     files = [i.split('/')[-1] for i in filelist]
     filestuple = tuple(files)
     pcr_text.insert(INSERT, filestuple)
    def loadSettings(self):
        settingFilePath = filedialog.askopenfilenames(
            parent=self,
            initialdir=self.home,
            title='Choose the settings file to load',
            filetypes=[("Setting files", ".fcntm"), ("All files", ".*")],
            multiple=False)
        if not settingFilePath:
            return

        with open(settingFilePath[0], 'r') as f:
            settings = f.read().split('\n')
        settings = list(map(lambda s: s.strip('\t'), settings))
        orgTest = [
            settings[0] == 'Output folder:',
            settings[2] == "Analysis ('voxel' or 'region'):",
            settings[4] == 'Number of parallel processes:',
            settings[6] == "Priors stored as ('h5' or 'nii'):",
            settings[8] == 'Position of the subjects ID in their path:',
            settings[10] == 'Mask the output:',
            settings[12] == 'Number of subjects:',
            settings[14] == 'Number of masks:',
            settings[16] == "Subject's BOLD paths:",
            settings[16 + int(settings[13]) +
                     2] == "Masks for voxelwise analysis:"
        ]
        if not all(orgTest):
            messagebox.showwarning('Bad file',
                                   'The file is not properly organised.',
                                   parent=self)
            return

        try:
            self.outDir.set(settings[1])
            self.maskOutput.set(int(settings[11]))
            if settings[3] in ('region', 'voxel'):
                self.ana_type.set(settings[3])
            else:
                messagebox.showwarning(
                    'Bad value',
                    f"Bad analysis type, should be 'region' or 'voxel', but is '{settings[3]}'",
                    parent=self)
                return

            try:
                int(settings[5])
            except:
                messagebox.showwarning(
                    'Bad value',
                    'The number of processes should be an integer',
                    parent=self)
                return
            self.nb_parallel_proc.set(settings[5])

            if settings[7] in ('h5', 'nii'):
                self.priors.set(settings[7])
            else:
                messagebox.showwarning(
                    'Bad value',
                    f"Bad prior type, should be 'h5' or 'nii', but is '{settings[7]}'",
                    parent=self)
                return

            try:
                int(settings[9])
            except:
                messagebox.showwarning(
                    'Bad value',
                    "The posistion of the subject's ID should be an integer",
                    parent=self)
                return

            self.bold_paths = []
            self.nbFiles.set(int(settings[13]))
            for isub in range(17, 17 + int(settings[13])):
                self.bold_paths.append(settings[isub])
            if settings[9] == "-1":
                self.subInPath.set('0')
                self.exSubName.set('Ex: ')
                self.exPath = ()
            else:
                self.subInPath.set(settings[9])
                self.exPath = tuple(
                    filter(
                        None,
                        os.path.normpath(self.bold_paths[0]).split(
                            os.path.sep)))
                self.posSubName.config(to=len(self.exPath) - 1)
                self.exSubName.set('Ex: ' +
                                   self.exPath[int(self.subInPath.get())])

            self.mask_paths = []
            self.nbMasks.set(int(settings[15]))
            startline = 19 + int(settings[13])
            stopline = startline + int(settings[15])
            for isub in range(startline, stopline):
                self.mask_paths.append(settings[isub])

            if len(settings) > 19 + int(settings[13]) + int(settings[15]):
                sett_tail = "".join(
                    settings[19 + int(settings[13]) +
                             int(settings[15]):])  # convert to 1 long string
                if "###" in sett_tail:
                    indStop = sett_tail.find("###")
                    sett_tail = sett_tail[:indStop]
                sett_tail = "".join(
                    sett_tail.split())  # remove all whitespaces
                if sett_tail:  # Check if there is anything left
                    messagebox.showwarning(
                        'More data than expected in the file',
                        ('There are non-empty lines trailing after the last considered line '
                         'in the settings file.\n'
                         'Check if the number of files announced is the same as the actual '
                         'number of paths written in the file.'),
                        parent=self)
        except:
            messagebox.showwarning(
                'Bad file',
                'There is a problem with the setting file. Check if its syntax is correct.',
                parent=self)
Example #53
0
 def open_filenames(self):
     # 调用askopenfilenames方法获取多个文件的文件名
     print(filedialog.askopenfilenames(title='打开多个文件',
         filetypes=[("文本文件", "*.txt"), ('Python源文件', '*.py')], # 只处理的文件类型
         initialdir='g:/')) # 初始目录 
Example #54
0
 def get_source_video_path(self):
     # 获取到需要添加片头的视频
     source_video_path = filedialog.askopenfilenames(title="选择视频")
     self.source_entry.delete(0, END)
     self.source_entry.insert(0, source_video_path)
    def AnalyzeCMMspectralvar(self):

        file_path = filedialog.askopenfilenames(
            title="Please select the cmm summary files")
        directory = str(Path(file_path[0]).parent.parent) + '\\resultFilesCMM'
        if not os.path.exists(directory):
            os.makedirs(directory)
            os.chdir(directory)
        else:
            os.chdir(directory)

        for pathtoread in file_path:
            name = os.path.split(pathtoread)[-1].split(".")[
                0]  #sample name is the file name

            with open(pathtoread) as f:
                reader = csv.reader(f, delimiter="\t")
                d = list(reader)

            VocFor = []
            VocRev = []
            JscFor = []
            JscRev = []
            FFFor = []
            FFRev = []
            PmppFor = []
            PmppRev = []
            VmppFor = []
            VmppRev = []
            JmppFor = []
            JmppRev = []
            RocFor = []
            RocRev = []
            RscFor = []
            RscRev = []
            illumination = []

            for i in range(
                    1, len(d)
            ):  #we suppose here that the cell was scanned in both directions (forward and reverse) and that both data will be found for all illumination settings
                if '_rev' in d[i][2]:
                    VocRev.append(float(d[i][3]))
                    JscRev.append(float(d[i][4]))
                    FFRev.append(float(d[i][5]))
                    PmppRev.append(float(d[i][6]))
                    RocRev.append(float(d[i][7]))
                    RscRev.append(float(d[i][8]))
                    VmppRev.append(float(d[i][9]))
                    JmppRev.append(float(d[i][10]))
                else:
                    illumination.append(d[i][2])
                    VocFor.append(float(d[i][3]))
                    JscFor.append(float(d[i][4]))
                    FFFor.append(float(d[i][5]))
                    PmppFor.append(float(d[i][6]))
                    RocFor.append(float(d[i][7]))
                    RscFor.append(float(d[i][8]))
                    VmppFor.append(float(d[i][9]))
                    JmppFor.append(float(d[i][10]))

            txtfile = [
                "illumination" + '\t' + "VocFor" + '\t' + "VocRev" + '\t' +
                "JscFor" + '\t' + "JscRev" + '\t' + "FFFor" + '\t' + "FFRev" +
                '\t' + "PmppFor" + '\t' + "PmppRev" + '\t' + "RocFor" + '\t' +
                "RscRev" + '\t' + "VmppFor" + '\t' + "VmppRev" + '\t' +
                "JmppFor" + '\t' + "JmppRev" + '\n'
            ]
            for i in range(len(illumination)):
                txtfile.append(illumination[i] + '\t' + str(VocFor[i]) + '\t' +
                               str(VocRev[i]) + '\t' + str(JscFor[i]) + '\t' +
                               str(JscRev[i]) + '\t' + str(FFFor[i]) + '\t' +
                               str(FFRev[i]) + '\t' + str(PmppFor[i]) + '\t' +
                               str(PmppRev[i]) + '\t' + str(RocFor[i]) + '\t' +
                               str(RscRev[i]) + '\t' + str(VmppFor[i]) + '\t' +
                               str(VmppRev[i]) + '\t' + str(JmppFor[i]) +
                               '\t' + str(JmppRev[i]) + '\n')
            file = open(name + '_FR.txt', 'w')
            file.writelines("%s" % item for item in txtfile)
            file.close()

            fig = plt.figure(figsize=(10, 12))
            Vocsubfig = fig.add_subplot(421)
            Jscsubfig = fig.add_subplot(422)
            FFsubfig = fig.add_subplot(423)
            Effsubfig = fig.add_subplot(424)
            Rocsubfig = fig.add_subplot(425)
            Rscsubfig = fig.add_subplot(426)
            Vmppsubfig = fig.add_subplot(427)
            Jmppsubfig = fig.add_subplot(428)

            Vocsubfig.set_ylabel('Voc (mV)')
            Vocsubfig.plot(illumination, VocFor, 'ro')
            Vocsubfig.plot(illumination, VocRev, 'bo')
            Jscsubfig.set_ylabel('Jsc (mA/cm2)')
            Jscsubfig.plot(illumination, JscFor, 'ro')
            Jscsubfig.plot(illumination, JscRev, 'bo')
            FFsubfig.set_ylabel('FF (%)')
            FFsubfig.plot(illumination, FFFor, 'ro')
            FFsubfig.plot(illumination, FFRev, 'bo')
            Effsubfig.set_ylabel('Eff (%)')
            Effsubfig.plot(illumination, PmppFor, 'ro')
            Effsubfig.plot(illumination, PmppRev, 'bo')
            Rocsubfig.set_ylabel('Roc ()')
            Rocsubfig.plot(illumination, RocFor, 'ro')
            Rocsubfig.plot(illumination, RocRev, 'bo')
            Rscsubfig.set_ylabel('Rsc ()')
            Rscsubfig.plot(illumination, RscFor, 'ro')
            Rscsubfig.plot(illumination, RscRev, 'bo')
            Vmppsubfig.set_ylabel('Vmpp (mV)')
            Vmppsubfig.plot(illumination, VmppFor, 'ro')
            Vmppsubfig.plot(illumination, VmppRev, 'bo')
            Jmppsubfig.set_ylabel('Jmpp (mA/cm2)')
            Jmppsubfig.plot(illumination, JmppFor, 'ro')
            Jmppsubfig.plot(illumination, JmppRev, 'bo')

            Vocsubfig.annotate(name + " - red=Forward; blue=Reverse",
                               xy=(0.6, 1.08),
                               xycoords='axes fraction',
                               fontsize=12,
                               horizontalalignment='left',
                               verticalalignment='bottom')

            plt.savefig(name + ".png", dpi=300, transparent=False)

            plt.close()
    def TruePhaseAvg(self):

        file_path = filedialog.askopenfilenames()
        try:
            folder = file_path[0].split('/')
        except:
            return

        path = ''
        for i in range(0, len(folder) - 1):
            path = path + folder[i] + "/"
        path = path + 'Resolution.txt'

        try:
            with open(path, 'r') as f:
                for line in f.readlines():
                    category, value = line.strip().split(';')
                self.deltaT = float(value)
                print(self.deltaT)
        except:
            self.deltaT = FileHandle.getResolution()
            print(self.deltaT)
        self.LoadCsvBar.setMaximum(len(file_path))
        self.show()
        arraylist = []
        try:
            for numb, i in enumerate(file_path):
                avg = []
                Timearray = []
                oneax = True
                self.LoadCsvBar.setValue(numb + 1)
                QtGui.QGuiApplication.processEvents()
                with open(i) as csv_file:
                    reader = csv.reader(csv_file, delimiter=';')

                    for row in reader:
                        if len(row) == 2:
                            Timearray.append(float(row[0]))
                            avg.append(float(row[1]))
                            oneax = False
                        else:
                            avg.append(float(row[0]))

                arraylist.append(np.asarray(avg))

        except:
            None

        length = 0
        cnt = 0
        for i in arraylist:
            if length == 0:
                length = len(i)

            if length > len(i):
                length = len(i)

            cnt = cnt + 1

        avg = np.zeros(length)

        for i in arraylist:

            avg = avg + i[0:length]

        self.close()
        print(cnt)
        avg = np.true_divide(avg, cnt)

        Timearray = np.arange(0, length, 1) * self.deltaT

        FileHandle.SaveData(Timearray, avg)

        plt.plot(Timearray, avg)
        plt.show()
Example #57
0
def main(argv):
    config = read_parser(argv, Inputs, InputsOpt_Defaults)

    if config['mode'] == 'normal_modulation':
        print('caca')
        fs = 1000000.
        dt = 1. / fs
        tr = 1.
        thr = 0.5
        alpha_bursts = 130.
        dura_bursts = 0.001
        frec_bursts = 92000.
        amort_bursts = 7887.
        std_add_noise = 0.1
        # std_phase_noise = 0.0
        std_mult_noise = 0.0001
        max_rint = 2

        Noise = np.random.RandomState(seed=1)
        t = np.arange(0, tr, dt)
        # phase_noise = 0.5*Noise.normal(1,std_phase_noise,len(t))
        # phase_noise = np.sin(2 * np.pi * t)

        # xc = signal.square(2*np.pi*alpha_bursts*t, duty=phase_noise)
        # rect = signal.square(2*np.pi*alpha_bursts*t, duty=phase_noise)

        xc = signal.square(2 * np.pi * alpha_bursts * t)
        rect = signal.square(2 * np.pi * alpha_bursts * t)

        # plt.plot(xc)
        # plt.show()

        n = len(xc)
        add_noise = Noise.normal(0, std_add_noise, n)
        mult_noise = Noise.normal(1, std_mult_noise, n)

        index = []
        for i in range(n - 1):
            if xc[i] < thr and xc[i + 1] >= thr:
                index.append(i)
        index = np.array(index)

        nidx = len(index)
        # rand_int = Noise.randint(0,max_rint,nidx)

        tb = np.arange(0, dura_bursts, dt)
        burst = np.sin(2 * np.pi * frec_bursts * tb) * np.exp(
            -amort_bursts * tb)
        nb = len(burst)
        # print(rand_int)

        # count = 0
        for idx in index:
            # print(count)
            xc[idx:idx + nb] += burst
            # if count != nidx -1:
            # xc[idx + rand_int[idx] : idx + rand_int[idx] + nb] += burst[0:]
            # else:
            # xc[idx:idx+nb] += burst
            # count += 1

        x = xc - rect

        # add_noise = np.random.normal(0,std_add_noise,n)
        # mult_noise = np.random.normal(1,std_mult_noise,n)

        x += add_noise
        x = x * mult_noise

        X, f, df = mag_fft(x, fs)

        # print(signal_rms(x))
        plt.plot(t, x)
        plt.show()

        plt.plot(f, X)
        plt.show()

    elif config['mode'] == 'normal_modulation_2':
        print('caca')
        fs = 1000000.
        dt = 1. / fs
        tr = 2.
        thr = 0.5
        alpha_bursts = 300.
        dura_bursts = 0.001
        frec_bursts = 92000.
        amort_bursts = 7887.
        planets = 3.
        carrier = 5.

        std_add_noise = 0.2
        std_phase_noise = 0.01
        std_mult_noise = 0.001

        # std_add_noise = 0.1
        # std_phase_noise = 0.01
        # std_mult_noise = 0.001

        max_rint = 2

        Noise = np.random.RandomState(seed=1)
        t = np.arange(0, tr, dt)
        phase_noise = 0.5 * Noise.normal(1, std_phase_noise, len(t))
        # phase_noise = Noise.uniform(0.5,0.5+0.05,len(t))
        # plt.plot(phase_noise, 'k')
        # plt.show()

        # phase_noise = np.sin(2 * np.pi * t)

        xc = signal.square(2 * np.pi * alpha_bursts * t, duty=phase_noise)
        rect = signal.square(2 * np.pi * alpha_bursts * t, duty=phase_noise)

        # xc = signal.square(2*np.pi*alpha_bursts*t)
        # rect = signal.square(2*np.pi*alpha_bursts*t)

        # plt.plot(xc)
        # plt.show()

        n = len(xc)
        add_noise = Noise.normal(0, std_add_noise, n)
        mult_noise = Noise.normal(1, std_mult_noise, n)

        index = []
        for i in range(n - 1):
            if xc[i] < thr and xc[i + 1] >= thr:
                index.append(i)
        index = np.array(index)

        nidx = len(index)
        # rand_int = Noise.randint(0,max_rint,nidx)

        tb = np.arange(0, dura_bursts, dt)
        burst = np.sin(2 * np.pi * frec_bursts * tb) * np.exp(
            -amort_bursts * tb)
        nb = len(burst)
        # print(rand_int)

        # count = 0
        for idx in index:
            # print(count)
            xc[idx:idx + nb] += burst
            # if count != nidx -1:
            # xc[idx + rand_int[idx] : idx + rand_int[idx] + nb] += burst[0:]
            # else:
            # xc[idx:idx+nb] += burst
            # count += 1

        x = xc - rect

        # add_noise = np.random.normal(0,std_add_noise,n)
        # mult_noise = np.random.normal(1,std_mult_noise,n)

        x += add_noise
        x = x * mult_noise

        mod = np.ones(n) + 0.3 * np.cos(2 * np.pi * planets * carrier * t)
        x = x * mod

        X, f, df = mag_fft(x, fs)

        x_env = hilbert_demodulation(x)
        X_env, f_env, df_env = mag_fft(x_env, fs)

        # print(signal_rms(x))
        plt.plot(t, x)
        plt.show()

        # plt.plot(f, X)
        # plt.show()

        plt.plot(f_env, X_env, 'g-o')
        plt.show()

    elif config['mode'] == 'gearbox_simulator':
        #+++++++++Simulation Data
        fs = 1000000.
        dt = 1. / fs
        tr = 1.
        thr = 0.5
        alpha_bursts = 300.
        dura_bursts = 0.001
        frec_bursts = 92000.
        amort_bursts = 7887.
        planets = 3.
        carrier = 5.

        std_add_noise = 0.2  #0.2
        std_phase_noise = 0.03  #0.02
        std_mult_noise = 0.001  #0.001

        amp_mod_1 = 0.35  #0.3
        amp_mod_2 = 0.95  #0.5

        #+++++++++++Time Array
        t = np.arange(0, tr, dt)
        n = len(t)

        #Noise Generator
        Noise = np.random.RandomState(seed=1)
        phase_noise = 0.5 * Noise.normal(1, std_phase_noise, n)
        add_noise = Noise.normal(0, std_add_noise, n)
        mult_noise = Noise.normal(1, std_mult_noise, n)

        #+++++++++++++Parent Signals
        #Train Pulses
        xc = signal.square(2 * np.pi * alpha_bursts * t, duty=phase_noise)
        rect = signal.square(2 * np.pi * alpha_bursts * t, duty=phase_noise)

        index = []
        for i in range(n - 1):
            if xc[i] < thr and xc[i + 1] >= thr:
                index.append(i)
        index = np.array(index)
        nidx = len(index)

        #Bursts
        tb = np.arange(0, dura_bursts, dt)
        burst = np.sin(2 * np.pi * frec_bursts * tb) * np.exp(
            -amort_bursts * tb)
        nb = len(burst)

        for idx in index:
            xc[idx:idx + nb] += burst

        #No modulated signal
        x = xc - rect
        plt.plot(x, 'k')
        plt.show()

        x += add_noise
        x = x * mult_noise

        #+++++++++++++Operational Modulations
        #Distance Pitch-Sensor
        mod_1 = np.ones(n) + amp_mod_1 * np.cos(
            2 * np.pi * planets * carrier * t)
        x = x * mod_1

        #Local Fault Ring Gear
        mod_2 = np.ones(n) + amp_mod_2 * signal.square(
            2 * np.pi * planets * carrier * t, duty=0.0075)

        # mod_2 = np.ones(n) + amp_mod_2*signal.sawtooth(2*np.pi*planets*carrier*t, width=0.25)

        plt.plot(mod_2, 'k')
        plt.show()

        x = x * mod_2

        #+++++++++++++Signal Processing
        #Spectrum
        X, f, df = mag_fft(x, fs)

        #Envelope
        x_env = hilbert_demodulation(x)

        #Envelope spectrum
        X_env, f_env, df_env = mag_fft(x_env, fs)

        #+++++++++++++Plots
        plt.plot(t, x)
        plt.show()

        plt.plot(f_env, X_env, 'g')
        plt.show()

    elif config['mode'] == 'gearbox_simulator_2':
        #+++++++++Simulation Data
        fs = 1000000.
        dt = 1. / fs
        tr = 0.25
        thr = 0.5
        alpha_bursts = 300.
        dura_bursts = 0.001
        frec_bursts = 92000.
        amort_bursts = 7887.
        planets = 3.
        carrier = 5.

        std_add_noise = 0.15  #0.15
        std_phase_noise = 0.0005  #0.0005
        std_mult_noise = 0.001  #0.001

        amp_mod_1 = 0.4  #0.4 sinus
        amp_mod_2 = 0.4  #0.4 local

        #+++++++++++Time Array
        t = np.arange(0, tr, dt)
        n = len(t)

        #Noise Generator
        Noise = np.random.RandomState(seed=1)
        phase_noise = 0.5 * Noise.normal(1, std_phase_noise, n)
        add_noise = Noise.normal(0, std_add_noise, n)
        mult_noise = Noise.normal(1, std_mult_noise, n)

        #+++++++++++++Parent Signals
        #Train Pulses
        xc = signal.square(2 * np.pi * alpha_bursts * t, duty=phase_noise)
        rect = signal.square(2 * np.pi * alpha_bursts * t, duty=phase_noise)

        index = []
        for i in range(n - 1):
            if xc[i] < thr and xc[i + 1] >= thr:
                index.append(i)
        index = np.array(index)
        nidx = len(index)

        #Bursts
        tb = np.arange(0, dura_bursts, dt)
        burst = np.sin(2 * np.pi * frec_bursts * tb) * np.exp(
            -amort_bursts * tb)
        nb = len(burst)

        for idx in index:
            xc[idx:idx + nb] += burst
            # if idx%15 != 0:
            # xc[idx:idx+nb] += burst
            # else:
            # xc[idx:idx+nb] += burst*10

        #No modulated signal
        x = xc - rect

        #+++++++++++++Operational Modulations
        # #Distance Pitch-Sensor Sinusoidal
        mod_s = np.ones(n) + amp_mod_1 * np.cos(
            2 * np.pi * planets * carrier * t)

        #Local Fault Ring Gear Pulse
        mod_p = np.ones(n) + amp_mod_2 * signal.square(
            2 * np.pi * planets * carrier * t, duty=0.0095)

        x = x * mod_p
        add_noise = add_noise * mod_p

        # x = x*mod_s
        add_noise = add_noise * mod_s

        #+++++++++++++Noise
        x += add_noise
        x = x * mult_noise

        # plt.plot(x)
        # plt.show()

        #+++++++++++++Special Burst
        thr = 1.
        index = []
        for i in range(n - 1):
            if x[i] < thr and x[i + 1] >= thr:
                print('special burst!')
                index.append(i)
        index = np.array(index)
        nidx = len(index)

        #Bursts
        tb = np.arange(0, dura_bursts, dt)
        burst = np.sin(2 * np.pi * frec_bursts * 2 * tb + np.pi / 8) * np.exp(
            -amort_bursts * 1.5 * tb)
        nb = len(burst)
        # print('!!', nb)
        # print(len(x[100-42:100-42+nb]))

        # print(type(x[25-42:25-42+nb]))
        # print(type(burst))
        # a = x[25-42:25-42+nb] + x[25-42:25-42+nb]
        # x[1:11] = np.arange(10)
        # sys.exit()

        for idx in index:
            # print(idx)
            # print(len(x[idx-42:idx-42+nb]))
            # print(len(1.3*burst))
            # aaa = x[idx-42:idx-42+nb] + 1.3*burst
            x[idx - 42:idx - 42 + nb] += 1.3 * burst
            # x[idx-42:idx-42+nb] = aaa

        plt.plot(t, x, 'r')
        plt.show()

        #+++++++++++++Signal Processing
        #Spectrum
        X, f, df = mag_fft(x, fs)
        X = 20 * np.log10(X / 1.e-6)
        # plt.plot(X)
        # plt.show()
        #Envelope
        x_env = hilbert_demodulation(x)

        #Envelope spectrum
        X_env, f_env, df_env = mag_fft(x_env, fs)
        X_env = 20 * np.log10(X_env / 1.e-6)

        # # save_pickle('simulated_AE_mod_fault_frec.pkl', x)
        # # x = list(x)
        # # x = np.array(x)
        # mydict = {config['channel']:x}
        # scipy.io.savemat(filename[:-5] + '.mat', mydict)
        # print('Signal was saved as .mat. Analysis finalizes')
        # sys.exit()

        #+++++++++++++Plots
        name = 'SigProcessing_FftEnv_FftEnv_Mod_OnlyNoise'
        path_1 = 'C:\\Felix\\29_THESIS\\MODEL_A\\ChapterX_SigProcessing\\03_Figures\\'
        path_2 = 'C:\\Felix\\29_THESIS\\MODEL_A\\LATEX_Diss_FLn\\bilder\\Figures_SigProcessing\\'
        path_1b = path_1 + name + '.svg'
        path_2b = path_2 + name + '.pdf'
        style = {
            'xlabel': ['Frequency [Hz]', 'Frequency [Hz]'],
            'ylabel': ['Magnitude [dB$_{AE}$]', 'Magnitude [dB$_{AE}$]'],
            'legend': None,
            'title': ['Envelope spectrum', 'Envelope spectrum'],
            'customxlabels': None,
            'xlim': [[0., 50], [200, 400]],
            'ylim': [[20, 120.], [20, 120.]],
            'color': [None],
            'loc_legend': 'upper left',
            'legend_line': 'OFF',
            'vlines': None,
            'range_lines': None,
            'output': config['output'],
            'path_1': path_1b,
            'path_2': path_2b
        }

        #+++Envelope spectrum
        # 'xlabel':['Frequency [Hz]', 'Frequency [Hz]'], 'ylabel':['Magnitude [dB$_{AE}$]', 'Magnitude [dB$_{AE}$]'], 'legend':None, 'title':['Envelope spectrum', 'Envelope spectrum'], 'customxlabels':None, 'xlim':[[0.,50], [200,400]], 'ylim':None

        #+++Wfm?
        # 'xlabel':['Time [s]', 'Time [s]'], 'ylabel':['Amplitude [V]', 'Amplitude [V]'], 'legend':None, 'title':['Waveform', 'Envelope'], 'customxlabels':None, 'xlim':[[0.,0.25], [0.,0.25]], 'ylim':[[-3,3], [0,3]]

        #+++Wfm-Env Zoom
        # 'xlabel':['Time [ms]', 'Time [ms]'], 'ylabel':['Amplitude [V]', 'Amplitude [V]'], 'legend':None, 'title':['Waveform', 'Envelope'], 'customxlabels':None, 'xlim':[[66.5, 67.0], [66.5, 67.0]], 'ylim':[[-3,3], [0,3]]

        # +++Spectrum
        # ['xlabel':['Time [s]', 'Frequency [kHz]'], 'ylabel':['Amplitude [V]', 'Magnitude [dB$_{AE}$]'], 'legend':None, 'title':['Waveform', 'Spectrum'], 'customxlabels':None, 'xlim':[[0.,0.25], [0.,500]], 'ylim':[[-3,3], [0,100]]

        data = {'x': [f_env, f_env], 'y': [X_env, X_env]}
        # data = {'x':[t, t], 'y':[x, x_env]}
        # data = {'x':[t*1000, t*1000], 'y':[x, x_env]}
        # data = {'x':[t, f/1000.], 'y':[x, X]}

        plot2_thesis_new(data, style)

        # plt.plot(t, x)
        # plt.show()

        # plt.plot(f_env, X_env, 'g')
        # plt.show()

    elif config['mode'] == 'only_plot':
        tr = 1
        dt = 1. / 1000000.
        fs = 1 / dt
        #+++++++++++Time Array
        t = np.arange(0, tr, dt)

        root = Tk()
        root.withdraw()
        root.update()
        filepath = filedialog.askopenfilename()
        root.destroy()

        x = load_signal(filepath, channel='none')

        plt.plot(t, x, 'r')
        plt.show()

        #+++++++++++++Signal Processing
        #Spectrum
        X, f, df = mag_fft(x, fs)
        X = 20 * np.log10(X / 1.e-6)
        # plt.plot(X)
        # plt.show()
        #Envelope
        x_env = hilbert_demodulation(x)

        #Envelope spectrum
        X_env, f_env, df_env = mag_fft(x_env, fs)
        X_env = 20 * np.log10(X_env / 1.e-6)

        # # save_pickle('simulated_AE_mod_fault_frec.pkl', x)
        # # x = list(x)
        # # x = np.array(x)
        # mydict = {config['channel']:x}
        # scipy.io.savemat(filename[:-5] + '.mat', mydict)
        # print('Signal was saved as .mat. Analysis finalizes')
        # sys.exit()

        #+++++++++++++Plots
        name = 'SigProcessing_Wfm_Env_Mod_Zoom_Fault'
        path_1 = 'C:\\Felix\\29_THESIS\\MODEL_A\\ChapterX_SigProcessing\\03_Figures\\'
        path_2 = 'C:\\Felix\\29_THESIS\\MODEL_A\\LATEX_Diss_FLn\\bilder\\Figures_SigProcessing\\'
        path_1b = path_1 + name + '.svg'
        path_2b = path_2 + name + '.pdf'
        style = {
            'xlabel': ['Time [ms]', 'Time [ms]'],
            'ylabel': ['Amplitude [V]', 'Amplitude [V]'],
            'legend': None,
            'title': ['Waveform', 'Envelope'],
            'customxlabels': None,
            'xlim': [[66.5 * 2, 67.0 * 2], [66.5 * 2, 67.0 * 2]],
            'ylim': [[-4, 4], [0, 4]],
            'color': [None],
            'loc_legend': 'upper left',
            'legend_line': 'OFF',
            'vlines': None,
            'range_lines': None,
            'output': config['output'],
            'path_1': path_1b,
            'path_2': path_2b
        }

        #+++Envelope spectrum
        # 'xlabel':['Frequency [Hz]', 'Frequency [Hz]'], 'ylabel':['Magnitude [dB$_{AE}$]', 'Magnitude [dB$_{AE}$]'], 'legend':None, 'title':['Envelope spectrum', 'Envelope spectrum'], 'customxlabels':None, 'xlim':[[0.,50], [200,400]], 'ylim':None

        #+++Wfm?
        # 'xlabel':['Time [s]', 'Time [s]'], 'ylabel':['Amplitude [V]', 'Amplitude [V]'], 'legend':None, 'title':['Waveform', 'Envelope'], 'customxlabels':None, 'xlim':[[0.,0.25], [0.,0.25]], 'ylim':[[-3,3], [0,3]]

        #+++Wfm-Env Zoom
        # 'xlabel':['Time [ms]', 'Time [ms]'], 'ylabel':['Amplitude [V]', 'Amplitude [V]'], 'legend':None, 'title':['Waveform', 'Envelope'], 'customxlabels':None, 'xlim':[[66.5, 67.0], [66.5, 67.0]], 'ylim':[[-3,3], [0,3]]

        # +++Spectrum
        # ['xlabel':['Time [s]', 'Frequency [kHz]'], 'ylabel':['Amplitude [V]', 'Magnitude [dB$_{AE}$]'], 'legend':None, 'title':['Waveform', 'Spectrum'], 'customxlabels':None, 'xlim':[[0.,0.25], [0.,500]], 'ylim':[[-3,3], [0,100]]

        # data = {'x':[f_env, f_env], 'y':[X_env, X_env]}
        # data = {'x':[t, t], 'y':[x, x_env]}
        data = {'x': [t * 1000, t * 1000], 'y': [x, x_env]}
        # data = {'x':[t, f/1000.], 'y':[x, X]}

        plot2_thesis_new(data, style)

        # plt.plot(t, x)
        # plt.show()

        # plt.plot(f_env, X_env, 'g')
        # plt.show()

    elif config['mode'] == 'emd_simulation':
        print('Select IMFs')
        root = Tk()
        root.withdraw()
        root.update()
        Filepaths = filedialog.askopenfilenames()
        root.destroy()

        #+++++++++Simulation Signals
        fs = 1000000.
        Signals = []
        Spectra = []
        Names = []
        for filepath in Filepaths:
            print(filepath)
            Names.append('IMF ' + os.path.basename(filepath)[1])
            x = load_signal(filepath, channel=None)
            fft, f, df = mag_fft(x, fs)
            Signals.append(x)
            fft = 20 * np.log10(fft / 1.e-6)  #dbAE
            Spectra.append(fft)
        n = len(Signals[0])

        dt = 1. / fs
        tr = n / fs
        Names[0] = 'Signal'
        print(Names)
        #+++++++++++Time Array
        t = np.arange(0, tr, dt)

        #+++++++++++++Plots
        name = 'SigProcessing_Wfm_Burst_EMD_Mod_Fault'
        path_1 = 'C:\\Felix\\29_THESIS\\MODEL_A\\ChapterX_SigProcessing\\03_Figures\\'
        path_2 = 'C:\\Felix\\29_THESIS\\MODEL_A\\LATEX_Diss_FLn\\bilder\\Figures_SigProcessing\\'
        path_1b = path_1 + name + '.svg'
        path_2b = path_2 + name + '.pdf'
        ymax_ = -3
        ymin_ = 3
        style = {
            'xlabel':
            'Time [ms]',
            'ylabel':
            '[V]',
            'legend':
            None,
            'title':
            Names,
            'customxlabels':
            None,
            'xlim': [66.5, 67],
            'ylim': [[ymin_, ymax_], [ymin_, ymax_], [ymin_, ymax_],
                     [ymin_, ymax_], [ymin_, ymax_], [ymin_, ymax_]],
            'color': [None],
            'loc_legend':
            'upper left',
            'legend_line':
            'OFF',
            'vlines':
            None,
            'range_lines':
            None,
            'output':
            config['output'],
            'path_1':
            path_1b,
            'path_2':
            path_2b
        }
        # [0.05,0.08]
        # 'xlabel':'Time [ms]'
        # 'Amplitude [V]'
        # [[0,100], [0,100], [0,100], [0,100], [0,100], [0,100]]
        # 'Frequency [kHz]'
        # '[dB$_{AE}$]'

        # data = {'x':[t, t, t, t, t, t], 'y':[Signals[0], Signals[1], Signals[2], Signals[3], Signals[4], Signals[5]]}

        data = {
            'x': [t * 1000, t * 1000, t * 1000, t * 1000, t * 1000, t * 1000],
            'y': [
                Signals[0], Signals[1], Signals[2], Signals[3], Signals[4],
                Signals[5]
            ]
        }

        # data = {'x':[f/1000., f/1000., f/1000., f/1000., f/1000., f/1000.], 'y':[Spectra[0], Spectra[1], Spectra[2], Spectra[3], Spectra[4], Spectra[5]]}

        plot6_thesis_new_emd(data, style)

        # plt.plot(t, x)
        # plt.show()

        # plt.plot(f_env, X_env, 'g')
        # plt.show()

    else:
        print('unknown mode')
        sys.exit()

    return

def generate_master(img_list):
    master = np.zeros((SIZE, SIZE))
    for i in trange(SIZE):
        for j in range(SIZE):
            L = [array[i, j] for array in img_list]
            master[i, j] = np.median(L)
    return master


# Liste des images à étudier
Tk().withdraw(
)  # we don't want a full GUI, so keep the root window from appearing
# show an "Open" dialog box and return the path to the selected files
raw_list = askopenfilenames(title='select RAW files')
flat_list = askopenfilenames(title='select FLAT files')
offset_list = askopenfilenames(title='select OFFSET files')

# Extraire la taille des images
hdul = fits.open(raw_list[0])
SIZE = hdul[0].header['NAXIS1']

# Concatenation des données de chacune des images
raw_concat = [fits.getdata(image) for image in raw_list]
flat_concat = [fits.getdata(image) for image in flat_list]
offset_concat = [fits.getdata(image) for image in offset_list]

# Générer les master images
master_flat = generate_master(flat_concat)
master_offset = generate_master(offset_concat)
Example #59
0
# print instances #
###################
print(f'{"#"*(5+len(str(scan)))}\nScan {scan}\n{"#"*(5+len(str(scan)))}')
print('\n##############\nSetup instance\n##############')
print(setup)
print('\n#################\nDetector instance\n#################')
print(detector)

################
# preload data #
################
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilenames(initialdir=detector.scandir,
                                        filetypes=[("NPZ", "*.npz"),
                                                   ("NPY", "*.npy"),
                                                   ("CXI", "*.cxi"),
                                                   ("HDF5", "*.h5")])
nbfiles = len(file_path)
plt.ion()

obj, extension = util.load_file(file_path[0])
if extension == '.h5':
    comment = comment + '_mode'

print('\n###############\nProcessing data\n###############')
nz, ny, nx = obj.shape
print("Initial data size: (", nz, ',', ny, ',', nx, ')')
if len(original_size) == 0:
    original_size = obj.shape
print("FFT size before accounting for phasing_binning", original_size)
Example #60
0
    #root = easygui
    #root.iconbitmap(r'c:\Python32\DLLs\py.ico')
    #root.mainloop()

    #print(filename)
    easygui.msgbox("The task was completed" + pathToGet,
                   "diropenbox",
                   ok_button="Continue")
    sys.exit(0)


def path_leaf(path):
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)


if __name__ == '__main__':
    window = Tk()

    window.title("Welcome to LikeGeeks app")

    #window.mainloop()

    filez = fd.askopenfilenames(parent=window, title='Choose a file')

    pathToGet = r"C:\Users\jsebastia\Pictures\Saved Pictures\imagenCompressor\imagenesPrueba\saturnohd.jpg"

    print(filez)
    #main()