Ejemplo n.º 1
0
def load_file(filename, progress_callback=None, segment=None):
    file_size = os.path.getsize(filename)
    available = list(psutil.virtual_memory())[1]
    percent = list(psutil.virtual_memory())[2]
    # [total, available, percent, used, free, active, inactive, buffers, cached, shared] = list(psutil.virtual_memory())

    if file_size > available:
        qtutil.critical('Not enough memory. File is of size ' +
                        str(file_size) + ' and available memory is: ' +
                        str(available))
        raise MemoryError('Not enough memory. File is of size ' +
                          str(file_size) + ' and available memory is: ' +
                          str(available))

    if percent > 95:
        qtutil.warning('Your memory appears to be getting low.')

    if filename.endswith('.npy'):
        frames = load_npy(filename, progress_callback, segment)
        # if frames.dtype == 'float64':
        #     qtutil.critical("FLOAT64")
        #     raise MemoryError("FLOAT64")
    else:
        raise UnknownFileFormatError()
    return frames
Ejemplo n.º 2
0
  def plot_to_docks(self, video_path_to_plots_dict, area):
      if not video_path_to_plots_dict:
          return
      roi_names = list(list(video_path_to_plots_dict.values())[0].keys())
      video_paths = list(video_path_to_plots_dict.keys())

      # regroup ROIs of same type together and add to Docks dynamically
      plot_docks = range(len([i for i in self.area.docks.keys()]))
      plot_docs_cycle = cycle(plot_docks)
      for roi_name in roi_names:
          warning_issued = False
          plots_for_roi = []
          source_names = []
          for video_path in video_path_to_plots_dict.keys():
              root, ext = os.path.splitext(video_path)
              source_name = os.path.basename(root)
              source_names = source_names + [source_name]
              plots_for_roi = plots_for_roi + [video_path_to_plots_dict[video_path][roi_name]]

          # put all plots from one ROI on a single plot and place on one of the 4 docs
          next_dock = next(plot_docs_cycle)
          d = Dock(roi_name, size=(500, 200), closable=True)
          area.addDock(d, 'above', area.docks['d' + str(next_dock + 1)])
          doc_window = pg.GraphicsWindow(title="Dock plot")
          plot = doc_window.addPlot(title=roi_name)
          plot.setLabel('bottom', "Image Frames")
          plot.setLabel('left', "Activity")
          plot.addLegend()
          assert (len(plots_for_roi) == len(source_names))
          for i, (p, source_name) in enumerate(zip(plots_for_roi, source_names)):
              if i < len(brewer_colors):
                  color = brewer_colors[i].rgb
              else:
                  if not warning_issued:
                      qtutil.warning('Perceptual distinctiveness limit (12) reached. Resorting to Kelly colours. '
                                     'Please be careful with how you interpret your data')
                      warning_issued = True
                  if i < len(brewer_colors) + len(kelly_colors):
                      color = kelly_colors[i - len(brewer_colors)].rgb
                  else:
                      qtutil.critical(
                          'Colour limit reached. Please plot your data over multiple plots or output solely to csv')
                      return doc_window
              plot.plot(p, pen=color, name=source_name)
          d.addWidget(doc_window)

          # Save plot to file (backup)
          ps = [list(p) for p in plots_for_roi]
          ps_rows = list(zip(*ps))
          plot_out = os.path.join(os.path.dirname(video_paths[0]), roi_name + '_plots_backup.csv')
          with open(plot_out, 'w', newline='') as csvfile:
              writer = csv.writer(csvfile, delimiter=',',
                                  quotechar='|', quoting=csv.QUOTE_MINIMAL)
              writer.writerow(source_names)
              for i, row in enumerate(ps_rows):
                  writer.writerow([str(p) for p in row])

      # close placeholder docks
      for plot_dock in plot_docks:
          area.docks['d' + str(plot_dock + 1)].close()
Ejemplo n.º 3
0
    def avg_origin(self):
        """Set origin to averaged over all selected files' origins"""
        if not self.selected_videos:
            return

        relevant_files = []
        for selected_path in self.selected_videos:
            relevant_files = relevant_files + \
                             [pfs.get_project_file_from_key_item(self.project, 'path', selected_path)]

        # check to see if all selected files have an origin
        try:
            [file['origin'] for file in relevant_files]
        except KeyError:
            qtutil.warning(
                'One or more of your selected files have no origin. These will be ignored.'
            )

        #collect dict items that have origins
        orgs = [file.get("origin") for file in relevant_files]
        orgs = [x for x in orgs if x is not None]
        orgs = [ast.literal_eval(org) for org in orgs]

        # collect and avg origins
        (x_tot, y_tot) = (0, 0)
        for (x, y) in orgs:
            (x_tot, y_tot) = (x_tot + x, y_tot + y)
        no_orgs = len(relevant_files)
        (x_avg, y_avg) = (x_tot / no_orgs, y_tot / no_orgs)
        self.project['origin'] = (x_avg, y_avg)
        self.view.update()
        self.save()
        self.x_origin_changed.emit(x_avg)
        self.y_origin_changed.emit(y_avg)
    def sub_clicked(self):
        summed_filesize = 0
        for path in self.selected_videos:
            summed_filesize = summed_filesize + os.path.getsize(path)
        available = list(psutil.virtual_memory())[1]
        if summed_filesize > available:
            qtutil.critical("Not enough memory. Total is of size "+str(summed_filesize) +\
               " and available memory is: " + str(available))
            raise MemoryError("Not enough memory. Total is of size "+str(summed_filesize) +\
               " and available memory is: " + str(available))


        paths = self.selected_videos
        if len(paths) != 2:
            qtutil.warning('Select two files to subtract.')
            return
        frames = [file_io.load_file(f) for f in paths]
        min_len = min([len(f) for f in frames])
        frames = np.subtract(np.array(frames[0][0:min_len], dtype=np.float32),
                           np.array(frames[1][0:min_len], dtype=np.float32))
        frames = np.array(frames, dtype=np.float32)

        # First one has to take the name otherwise pfs.save_projects doesn't work
        manip = 'channel_sub'
        pfs.save_project(paths[0], self.project, frames, manip, 'video')
        pfs.refresh_list(self.project, self.video_list,
                         self.params[self.Labels.video_list_indices_label],
                         self.Defaults.list_display_type,
                         self.params[self.Labels.last_manips_to_display_label])
Ejemplo n.º 5
0
    def div_clicked(self):
        summed_filesize = 0
        for path in self.selected_videos:
            summed_filesize = summed_filesize + os.path.getsize(path)
        available = list(psutil.virtual_memory())[1]
        if summed_filesize > available:
            qtutil.critical("Not enough memory. Total is of size "+str(summed_filesize) +\
               " and available memory is: " + str(available))
            raise MemoryError("Not enough memory. Total is of size "+str(summed_filesize) +\
               " and available memory is: " + str(available))


        paths = self.selected_videos
        if len(paths) != 2:
            qtutil.warning('Select 2 files to divide.')
            return
        frames = [file_io.load_file(f) for f in paths]
        min_len = min([len(f) for f in frames])
        frames = np.divide(np.array(frames[0][0:min_len], dtype=np.float32),
                           np.array(frames[1][0:min_len], dtype=np.float32))
        if np.isinf(frames).any():
            qtutil.critical("Infinite values detected. Are you sure you are dividing appropriate image stacks?")
            qtutil.critical('Output will appear blank. Output is too small when scaled against infinite')
        frames[np.isnan(frames)] = 0  # todo: is this okay?
        frames = np.array(frames, dtype=np.float32)

        # First one has to take the name otherwise pfs.save_projects doesn't work
        manip = 'channel_div'
        pfs.save_project(paths[0], self.project, frames, manip, 'video')
        pfs.refresh_list(self.project, self.video_list,
                         self.params[self.Labels.video_list_indices_label],
                         self.Defaults.list_display_type,
                         self.params[self.Labels.last_manips_to_display_label])
Ejemplo n.º 6
0
  def avg_origin(self):
    """Set origin to averaged over all selected files' origins"""
    if not self.selected_videos:
        return

    relevant_files = []
    for selected_path in self.selected_videos:
        relevant_files = relevant_files + \
                         [pfs.get_project_file_from_key_item(self.project, 'path', selected_path)]

    # check to see if all selected files have an origin
    try:
        [file['origin'] for file in relevant_files]
    except KeyError:
        qtutil.warning('One or more of your selected files have no origin. These will be ignored.')

    #collect dict items that have origins
    orgs = [file.get("origin") for file in relevant_files]
    orgs = [x for x in orgs if x is not None]
    orgs = [ast.literal_eval(org) for org in orgs]

    # collect and avg origins
    (x_tot, y_tot) = (0, 0)
    for (x, y) in orgs:
      (x_tot, y_tot) = (x_tot+x, y_tot+y)
    no_orgs = len(relevant_files)
    (x_avg, y_avg) = (x_tot / no_orgs, y_tot / no_orgs)
    self.project['origin'] = (x_avg, y_avg)
    self.view.update()
    self.save()
    self.x_origin_changed.emit(x_avg)
    self.y_origin_changed.emit(y_avg)
Ejemplo n.º 7
0
 def special_warning(self):
     qtutil.warning("Please note that you can move the ROIs in this view and even right click and save them which"
                    " does alter this ROI for this project. However, note that the coordinates "
                    "associated with the ROI are not automatically shifted. Therefore, plugins that explicitly "
                    "use the coordinates such as seed pixel correlation will not use your moved ROI \n"
                    "\n"
                    "Make changes here to see where you want your ROI to be and then make changes "
                    "in your csv and reload")
Ejemplo n.º 8
0
    def execute_primary_function(self, input_paths=None):
        if not input_paths:
            if not self.selected_videos:
                return
            else:
                selected_videos = self.selected_videos
        else:
            selected_videos = input_paths

        progress_global = QProgressDialog('Creating evoked average...',
                                          'Abort', 0, 100, self)
        progress_global.setAutoClose(True)
        progress_global.setMinimumDuration(0)

        def global_callback(x):
            progress_global.setValue(x * 100)
            QApplication.processEvents()

        filenames = selected_videos
        if len(filenames) < 2:
            qtutil.warning('Select multiple files to average.')
            return
        stacks = [np.load(f, mmap_mode='r') for f in filenames]
        lens = [len(stacks[x]) for x in range(len(stacks))]
        min_lens = np.min(lens)

        breadth = stacks[0].shape[1]
        length = stacks[0].shape[2]

        trig_avg = np.empty((min_lens, length, breadth),
                            np.load(filenames[0], mmap_mode='r').dtype)
        for frame_index in range(min_lens):
            global_callback(frame_index / min_lens)
            frames_to_avg = [
                stacks[stack_index][frame_index]
                for stack_index in range(len(stacks))
            ]
            frames_to_avg = np.array(frames_to_avg, dtype=np.float32)
            avg = np.mean(frames_to_avg, axis=0, dtype=np.float32)
            trig_avg[frame_index] = avg
        global_callback(1)
        manip = self.Defaults.manip + '_' + str(len(filenames))
        output_path = pfs.save_project(filenames[0], self.project, trig_avg,
                                       manip, 'video')
        pfs.refresh_list(self.project, self.video_list,
                         self.params[self.Labels.video_list_indices_label],
                         self.Defaults.list_display_type,
                         self.params[self.Labels.last_manips_to_display_label])
        return output_path
Ejemplo n.º 9
0
 def import_files(self, filenames):
   for filename in filenames:
     if filename in [f['path'] for f in self.project.files]:
       continue
     try:
       filename = self.import_file(filename)
     except NotConvertedError:
       qtutil.warning('Skipping file \'{}\' since not converted.'.format(filename))
     except FileAlreadyInProjectError as e:
       qtutil.warning('Skipping file \'{}\' since already in project.'.format(e.filename))
     except:
       qtutil.critical('Import of \'{}\' failed:\n'.format(filename) +\
         traceback.format_exc())
     else:
       self.listview.model().appendRow(QStandardItem(filename))
Ejemplo n.º 10
0
 def import_files(self, filenames):
   imported_paths = []
   for filename in filenames:
     if filename in [f['path'] for f in self.project.files]:
       continue
     try:
       imported_path = self.import_file(filename)
     except NotConvertedError:
       qtutil.warning('Skipping file \'{}\' since not converted.'.format(filename))
     except:
       qtutil.critical('Import of \'{}\' failed:\n'.format(filename) +\
         traceback.format_exc())
     else:
       self.listview.model().appendRow(QStandardItem(imported_path))
       imported_paths = imported_paths + [imported_path]
   return imported_paths
Ejemplo n.º 11
0
 def concat_clicked(self):
     paths = self.selected_videos
     if len(paths) < 2:
         qtutil.warning('Select multiple files to concatenate.')
         return
     frames = [fileloader.load_file(f) for f in paths]
     frames = np.concatenate(frames)
     # concat_name = '_'.join(filenames) + '.npy'
     # concat_path = os.path.join(self.project.path, concat_name)
     # First one has to take the name otherwise pfs.save_projects doesn't work
     filenames = [os.path.basename(path) for path in paths]
     manip = 'concat_'+str(len(filenames))
     # long_ass_name = 'concat_'+'_concat_'.join(filenames[1:])
     # long_ass_name = long_ass_name.replace('.npy', '')
     pfs.save_project(paths[0], self.project, frames, manip, 'video')
     pfs.refresh_all_list(self.project, self.video_list)
 def import_files(self, filenames):
     for filename in filenames:
         if filename in [f['path'] for f in self.project.files]:
             continue
         try:
             filename = self.import_file(filename)
         except NotConvertedError:
             qtutil.warning(
                 'Skipping file \'{}\' since not converted.'.format(
                     filename))
         except FileAlreadyInProjectError as e:
             qtutil.warning(
                 'Skipping file \'{}\' since already in project.'.format(
                     e.filename))
         except:
             qtutil.critical('Import of \'{}\' failed:\n'.format(filename) + \
                             traceback.format_exc())
         else:
             self.listview.model().appendRow(QStandardItem(filename))
Ejemplo n.º 13
0
    def execute_primary_function(self, input_paths=None):
        if not input_paths:
            if not self.selected_videos:
                return
            else:
                selected_videos = self.selected_videos
        else:
            selected_videos = input_paths

        progress_global = QProgressDialog('Creating evoked average...', 'Abort', 0, 100, self)
        progress_global.setAutoClose(True)
        progress_global.setMinimumDuration(0)
        def global_callback(x):
            progress_global.setValue(x * 100)
            QApplication.processEvents()

        filenames = selected_videos
        if len(filenames) < 2:
            qtutil.warning('Select multiple files to average.')
            return
        stacks = [np.load(f, mmap_mode='r') for f in filenames]
        lens = [len(stacks[x]) for x in range(len(stacks))]
        min_lens = np.min(lens)

        breadth = stacks[0].shape[1]
        length = stacks[0].shape[2]

        trig_avg = np.empty((min_lens, length, breadth), np.load(filenames[0], mmap_mode='r').dtype)
        for frame_index in range(min_lens):
            global_callback(frame_index / min_lens)
            frames_to_avg = [stacks[stack_index][frame_index]
                             for stack_index in range(len(stacks))]
            frames_to_avg = np.array(frames_to_avg, dtype=np.float32)
            avg = np.mean(frames_to_avg, axis=0, dtype=np.float32)
            trig_avg[frame_index] = avg
        global_callback(1)
        manip = self.Defaults.manip + '_' + str(len(filenames))
        output_path = pfs.save_project(filenames[0], self.project, trig_avg, manip, 'video')
        pfs.refresh_list(self.project, self.video_list,
                         self.params[self.Labels.video_list_indices_label],
                         self.Defaults.list_display_type,
                         self.params[self.Labels.last_manips_to_display_label])
        return output_path
Ejemplo n.º 14
0
    def execute_primary_function(self, input_paths=None):
        if not input_paths:
            if not self.selected_videos:
                return
            else:
                selected_videos = self.selected_videos
        else:
            selected_videos = input_paths

        summed_filesize = 0
        for path in self.selected_videos:
            summed_filesize = summed_filesize + os.path.getsize(path)
        available = list(psutil.virtual_memory())[1]
        if summed_filesize > available:
            qtutil.critical("Not enough memory. Concatenated file is of size ~"+str(summed_filesize) +\
               " and available memory is: " + str(available))
            raise MemoryError("Not enough memory. Concatenated file is of size ~"+str(summed_filesize) +\
               " and available memory is: " + str(available))

        paths = selected_videos
        if len(paths) < 2:
            qtutil.warning('Select multiple files to concatenate.')
            return
        frames = [file_io.load_file(f) for f in paths]
        progress = MyProgressDialog('Concatenation', 'Concatenating files...',
                                    self)
        progress.show()
        progress.setValue(1)
        frames = np.concatenate(frames)
        progress.setValue(99)
        # First one has to take the name otherwise pfs.save_projects doesn't work
        filenames = [os.path.basename(path) for path in paths]
        manip = 'concat-' + str(len(filenames))
        output_path = pfs.save_project(paths[0], self.project, frames, manip,
                                       'video')
        pfs.refresh_list(self.project, self.video_list,
                         self.params[self.Labels.video_list_indices_label],
                         self.Defaults.list_display_type,
                         self.params[self.Labels.last_manips_to_display_label])
        progress.close()
        return [output_path]
Ejemplo n.º 15
0
    def trigger_average(self):
        filenames = self.table1.selected_paths()
        if len(filenames) < 2:
            qtutil.warning('Select multiple files to average.')
            return
        frames = [fileloader.load_file(f) for f in filenames]
        lens = [len(frames[x]) for x in range(len(frames))]
        min_lens = np.min(lens)

        length = frames[0].shape[1]
        breadth = frames[0].shape[2]

        trig_avg = np.empty([min_lens, length, breadth])
        for frame_set_index in range(min_lens):
            frames_to_avg = [frames[frame_index][frame_set_index]
                             for frame_index in range(len(frames))]
            frames_to_avg = np.concatenate(frames_to_avg)
            avg = np.mean(frames_to_avg, axis=0)
            trig_avg[frame_set_index] = avg
        pfs.save_project(os.path.join(self.project.path, str(uuid.uuid4())
                                      , self.project, trig_avg, 'trigger-avg'),'video')

        self.update_tables()
Ejemplo n.º 16
0
def save_file(path, data):
    file_size = data.nbytes
    available = list(psutil.virtual_memory())[1]
    percent = list(psutil.virtual_memory())[2]
    # [total, available, percent, used, free, active, inactive, buffers, cached, shared] = list(psutil.virtual_memory())

    if file_size > available:
        qtutil.critical('Memory warning. File is of size ' + str(file_size) +
                        ' and available memory is: ' + str(available))
        # del_msg = path + " might not be saved due to insufficient memory. " \
        #                  "If you attempt to save it, it may cause system instability. If you do abort then this file" \
        #                  "will be lost. Note that only this one file will be lost. Proceed?"
        # reply = QMessageBox.question(widget, 'File Save Error',
        #                              del_msg, QMessageBox.Yes, QMessageBox.No)
        # if reply == QMessageBox.No:
        #     raise MemoryError('Not enough memory. File is of size ' + str(file_size) +
        #                       ' and available memory is: ' + str(available))

    if percent > 95:
        qtutil.warning('Your memory appears to be getting low.')
    # total, used, free = psutil.disk_usage(os.path.dirname(path))
    # if data.nbytes > free:
    #     qtutil.critical('Not enough space on drive. File is of size ' + str(data.nbytes) +
    #                     ' and available space is: ' + str(free))
    #     raise IOError('Not enough space on drive. File is of size ' + str(data.nbytes) +
    #                     ' and available space is: ' + str(free))
    if os.path.isfile(path):
        os.remove(path)
    try:
        # if data.dtype == 'float64':
        #     qtutil.critical("FLOAT64")
        #     raise MemoryError("FLOAT64")
        np.save(path, data)
    except:
        qtutil.critical(
            'Could not save ' + path +
            '. This is likely due to running out of space on the drive')
Ejemplo n.º 17
0
    def div_clicked(self):
        summed_filesize = 0
        for path in self.selected_videos:
            summed_filesize = summed_filesize + os.path.getsize(path)
        available = list(psutil.virtual_memory())[1]
        if summed_filesize > available:
            qtutil.critical("Not enough memory. Total is of size "+str(summed_filesize) +\
               " and available memory is: " + str(available))
            raise MemoryError("Not enough memory. Total is of size "+str(summed_filesize) +\
               " and available memory is: " + str(available))

        paths = self.selected_videos
        if len(paths) != 2:
            qtutil.warning('Select 2 files to divide.')
            return
        frames = [file_io.load_file(f) for f in paths]
        min_len = min([len(f) for f in frames])
        frames = np.divide(np.array(frames[0][0:min_len], dtype=np.float32),
                           np.array(frames[1][0:min_len], dtype=np.float32))
        if np.isinf(frames).any():
            qtutil.critical(
                "Infinite values detected. Are you sure you are dividing appropriate image stacks?"
            )
            qtutil.critical(
                'Output will appear blank. Output is too small when scaled against infinite'
            )
        frames[np.isnan(frames)] = 0  # todo: is this okay?
        frames = np.array(frames, dtype=np.float32)

        # First one has to take the name otherwise pfs.save_projects doesn't work
        manip = 'channel_div'
        pfs.save_project(paths[0], self.project, frames, manip, 'video')
        pfs.refresh_list(self.project, self.video_list,
                         self.params[self.Labels.video_list_indices_label],
                         self.Defaults.list_display_type,
                         self.params[self.Labels.last_manips_to_display_label])
Ejemplo n.º 18
0
    def plot_triggered(self):
        # main_window = QMainWindow()
        # area = self.setup_docks()
        # main_window.setCentralWidget(area)
        # main_window.resize(2000, 900)
        # main_window.setWindowTitle("Window ID - " + str(uuid.uuid4()) +
        #                            ". Click Shift+F1 for help")
        # main_window.setWhatsThis("Use View All to reset a view\n"
        #                          "\n"
        #                          "The blue tabs have the name of the ROI for a particular plot. These tabs can be dragged "
        #                          "around to highlighted regions to the side of other tabs to split the dock or on top of "
        #                          "other plots to place the tab in that dock. \n"
        #                          "\n"
        #                          "right click any plot to see more options. One important one is mouse mode. In Mouse "
        #                          "mode 3 you can hold the left mouse button to pan and "
        #                          "In mouse mode 1 you can zoom in on a particular region by creating cropping it with the "
        #                          "left mouse button. In either mode the right mouse button can be used to adjust the shape "
        #                          "of the plot and the mouse wheel for zoom \n"
        #                          "\n"
        #                          "Use Export to save a particular plot's data to csv or save as an image after you are "
        #                          "satisfied with how graphical elements (see 'plot options') are arranged. "
        #                          "Note that backups csv's of all plots are made automatically and can be found in your "
        #                          "project directory")
        video_path_to_plots_dict = self.get_video_path_to_plots_dict()

        if len(video_path_to_plots_dict.keys()) == 1:
            # area = DockArea()
            # d1 = Dock("d1", size=(500, 200), closable=True)
            # area.addDock(d1)
            video_path = list(video_path_to_plots_dict.keys())[0]
            plot_title, ext = os.path.splitext(video_path)
            # d = Dock(video_path, size=(500, 200), closable=True)
            # area.addDock(d, 'above', area.docks['d1'])

            win = pg.GraphicsWindow(title="Single Image Stack Plot")
            plot = win.addPlot(title=plot_title)
            plot.setLabel('bottom', "Image Frames")
            plot.setLabel('left', "Activity")
            plot.addLegend()

            roi_names = list(video_path_to_plots_dict[video_path].keys())
            warning_issued = False
            for i, roi_name in enumerate(roi_names):
                p = video_path_to_plots_dict[video_path][roi_name]
                if i < len(brewer_colors):
                    color = brewer_colors[i].rgb
                else:
                    if not warning_issued:
                        qtutil.warning(
                            'Perceptual distinctiveness limit (12) reached. Resorting to Kelly colours. '
                            'Please be careful with how you interpret your data'
                        )
                        warning_issued = True
                    if i < len(brewer_colors) + len(kelly_colors):
                        color = kelly_colors[i - len(brewer_colors)].rgb
                    else:
                        qtutil.critical(
                            'Colour limit reached. Outputting to csv instead.')
                        # Save plot to file (backup)
                        ps = [
                            list(p) for p in list(
                                video_path_to_plots_dict[video_path].values())
                        ]
                        ps_rows = list(zip(*ps))
                        plot_out = os.path.join(os.path.dirname(video_path),
                                                roi_name + '_plots.csv')
                        with open(plot_out, 'w', newline='') as csvfile:
                            writer = csv.writer(csvfile,
                                                delimiter=',',
                                                quotechar='|',
                                                quoting=csv.QUOTE_MINIMAL)
                            writer.writerow(roi_names)
                            for i, row in enumerate(ps_rows):
                                writer.writerow([str(p) for p in row])
                plot.plot(p, pen=color, name=roi_name)
            self.open_dialogs.append(win)
            # d.addWidget(doc_window)
        else:
            # self.plot_to_docks(video_path_to_plots_dict, area)
            dock_window = DockWindowPlot(video_path_to_plots_dict, parent=self)
            dock_window.show()
            self.open_dialogs.append(dock_window)
Ejemplo n.º 19
0
    def plot_to_docks(self, video_path_to_plots_dict, area):
        if not video_path_to_plots_dict:
            return
        roi_names = list(list(video_path_to_plots_dict.values())[0].keys())
        video_paths = list(video_path_to_plots_dict.keys())

        # regroup ROIs of same type together and add to Docks dynamically
        plot_docks = range(len([i for i in self.area.docks.keys()]))
        plot_docs_cycle = cycle(plot_docks)
        for roi_name in roi_names:
            warning_issued = False
            plots_for_roi = []
            source_names = []
            for video_path in video_path_to_plots_dict.keys():
                root, ext = os.path.splitext(video_path)
                source_name = os.path.basename(root)
                source_names = source_names + [source_name]
                plots_for_roi = plots_for_roi + [
                    video_path_to_plots_dict[video_path][roi_name]
                ]

            # put all plots from one ROI on a single plot and place on one of the 4 docs
            next_dock = next(plot_docs_cycle)
            d = Dock(roi_name, size=(500, 200), closable=True)
            area.addDock(d, 'above', area.docks['d' + str(next_dock + 1)])
            doc_window = pg.GraphicsWindow(title="Dock plot")
            plot = doc_window.addPlot(title=roi_name)
            plot.setLabel('bottom', "Image Frames")
            plot.setLabel('left', "Activity")
            plot.addLegend()
            assert (len(plots_for_roi) == len(source_names))
            for i, (p,
                    source_name) in enumerate(zip(plots_for_roi,
                                                  source_names)):
                if i < len(brewer_colors):
                    color = brewer_colors[i].rgb
                else:
                    if not warning_issued:
                        qtutil.warning(
                            'Perceptual distinctiveness limit (12) reached. Resorting to Kelly colours. '
                            'Please be careful with how you interpret your data'
                        )
                        warning_issued = True
                    if i < len(brewer_colors) + len(kelly_colors):
                        color = kelly_colors[i - len(brewer_colors)].rgb
                    else:
                        qtutil.critical(
                            'Colour limit reached. Please plot your data over multiple plots or output solely to csv'
                        )
                        return doc_window
                plot.plot(p, pen=color, name=source_name)
            d.addWidget(doc_window)

            # Save plot to file (backup)
            ps = [list(p) for p in plots_for_roi]
            ps_rows = list(zip(*ps))
            plot_out = os.path.join(os.path.dirname(video_paths[0]),
                                    roi_name + '_plots_backup.csv')
            with open(plot_out, 'w', newline='') as csvfile:
                writer = csv.writer(csvfile,
                                    delimiter=',',
                                    quotechar='|',
                                    quoting=csv.QUOTE_MINIMAL)
                writer.writerow(source_names)
                for i, row in enumerate(ps_rows):
                    writer.writerow([str(p) for p in row])

        # close placeholder docks
        for plot_dock in plot_docks:
            area.docks['d' + str(plot_dock + 1)].close()
Ejemplo n.º 20
0
  def plot_triggered(self):
    # main_window = QMainWindow()
    # area = self.setup_docks()
    # main_window.setCentralWidget(area)
    # main_window.resize(2000, 900)
    # main_window.setWindowTitle("Window ID - " + str(uuid.uuid4()) +
    #                            ". Click Shift+F1 for help")
    # main_window.setWhatsThis("Use View All to reset a view\n"
    #                          "\n"
    #                          "The blue tabs have the name of the ROI for a particular plot. These tabs can be dragged "
    #                          "around to highlighted regions to the side of other tabs to split the dock or on top of "
    #                          "other plots to place the tab in that dock. \n"
    #                          "\n"
    #                          "right click any plot to see more options. One important one is mouse mode. In Mouse "
    #                          "mode 3 you can hold the left mouse button to pan and "
    #                          "In mouse mode 1 you can zoom in on a particular region by creating cropping it with the "
    #                          "left mouse button. In either mode the right mouse button can be used to adjust the shape "
    #                          "of the plot and the mouse wheel for zoom \n"
    #                          "\n"
    #                          "Use Export to save a particular plot's data to csv or save as an image after you are "
    #                          "satisfied with how graphical elements (see 'plot options') are arranged. "
    #                          "Note that backups csv's of all plots are made automatically and can be found in your "
    #                          "project directory")
    video_path_to_plots_dict = self.get_video_path_to_plots_dict()

    if len(video_path_to_plots_dict.keys()) == 1:
        # area = DockArea()
        # d1 = Dock("d1", size=(500, 200), closable=True)
        # area.addDock(d1)
        video_path = list(video_path_to_plots_dict.keys())[0]
        plot_title, ext = os.path.splitext(video_path)
        # d = Dock(video_path, size=(500, 200), closable=True)
        # area.addDock(d, 'above', area.docks['d1'])

        win = pg.GraphicsWindow(title="Single Image Stack Plot")
        plot = win.addPlot(title=plot_title)
        plot.setLabel('bottom', "Image Frames")
        plot.setLabel('left', "Activity")
        plot.addLegend()

        roi_names = list(video_path_to_plots_dict[video_path].keys())
        warning_issued = False
        for i, roi_name in enumerate(roi_names):
            p = video_path_to_plots_dict[video_path][roi_name]
            if i < len(brewer_colors):
                color = brewer_colors[i].rgb
            else:
                if not warning_issued:
                    qtutil.warning('Perceptual distinctiveness limit (12) reached. Resorting to Kelly colours. '
                                   'Please be careful with how you interpret your data')
                    warning_issued = True
                if i < len(brewer_colors) + len(kelly_colors):
                    color = kelly_colors[i - len(brewer_colors)].rgb
                else:
                    qtutil.critical(
                        'Colour limit reached. Outputting to csv instead.')
                    # Save plot to file (backup)
                    ps = [list(p) for p in list(video_path_to_plots_dict[video_path].values())]
                    ps_rows = list(zip(*ps))
                    plot_out = os.path.join(os.path.dirname(video_path), roi_name + '_plots.csv')
                    with open(plot_out, 'w', newline='') as csvfile:
                        writer = csv.writer(csvfile, delimiter=',',
                                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
                        writer.writerow(roi_names)
                        for i, row in enumerate(ps_rows):
                            writer.writerow([str(p) for p in row])
            plot.plot(p, pen=color, name=roi_name)
        self.open_dialogs.append(win)
        # d.addWidget(doc_window)
    else:
        # self.plot_to_docks(video_path_to_plots_dict, area)
        dock_window = DockWindowPlot(video_path_to_plots_dict, parent=self)
        dock_window.show()
        self.open_dialogs.append(dock_window)