<commit_before>from ScopeFoundry.data_browser import DataBrowser, DataBrowserView
import pyqtgraph as pg
import numpy as np
from scipy.misc import imread
import os
import pyqtgraph.dockarea
from qtpy import QtCore, QtWidgets
from pyqtgraph.graphicsItems.ROI import EllipseROI


class Gauss2DFitImgView(DataBrowserView):

    name = 'gauss2d_fit_img'
    
    def setup(self):
        
        self.ui = self.dockarea = pyqtgraph.dockarea.DockArea()
        self.imview = pg.ImageView()
        self.imview.getView().invertY(True) # uper left origin
        self.dockarea.addDock(name='Full Image', widget=self.imview)

        self.imview_roi = pg.ImageView()
        self.imview_roi.getView().invertY(True) # upper left origin
        self.dockarea.addDock(name='ROI Image', widget=self.imview_roi)

        self.imview_gauss = pg.ImageView()
        self.imview_gauss.getView().invertY(True) # upper left origin
        self.dockarea.addDock(name='Gauss Fit Image', widget=self.imview_gauss)
        
        
        self.rect_roi = pg.RectROI([20, 20], [100, 100], pen=(0,9))
        self.imview.getView().addItem(self.rect_roi)        
        self.rect_roi.sigRegionChanged[object].connect(self.on_change_rect_roi)

        self.info_label = QtWidgets.QLabel()
        self.dockarea.addDock(name='info', widget=self.info_label)

        
    def on_change_data_filename(self, fname):
        
        try:
            self.data = imread(fname)
            if len(self.data.shape) == 3:
                self.data = self.data.sum(axis=2)
                
            self.imview.setImage(self.data, axes=dict(x=1,y=0))
        except Exception as err:
            self.imview.setImage(np.zeros((10,10)))
            self.databrowser.ui.statusbar.showMessage("failed to load %s:\n%s" %(fname, err))
            raise(err)

        self.on_change_rect_roi()

        
    def is_file_supported(self, fname):
        _, ext = os.path.splitext(fname)
        return ext.lower() in ['.png', '.tif', '.tiff', '.jpg']


    def on_change_rect_roi(self, roi=None):
        # pyqtgraph axes are x,y, but data is stored in (frame, y,x, time)
        #roi_slice, roi_tr = self.rect_roi.getArraySlice(self.data, self.imview.getImageItem(), axes=(1,0))
        #self.rect_plotdata.setData(self.spec_x_array, self.hyperspec_data[roi_slice].mean(axis=(0,1))+1)
        
        self.roi_img = self.rect_roi.getArrayRegion(data=self.data, img=self.imview.getImageItem(), axes=(1,0)) 
        
        #print(self.roi_img.shape)
        
        self.imview_roi .setImage(self.roi_img, axes=dict(x=1,y=0)) #, axes=dict(x=1,y=0))
        #print("roi_slice", roi_slice)
        
        p,success = fitgaussian(self.roi_img)
        
        height, x, y, width_x, width_y, angle = p
        print(p)
        
        if success:
            
            self.info_label.setText("height:{}, x: {}, y: {}, width_x: {}, width_y: {}, angle: {}".format(*p))
            
            ny,nx = self.roi_img.shape
            X,Y = np.mgrid[:ny,:nx]
            self.gaus_img = gaussian(*p)(X,Y)
            
            self.imview_gauss.setImage(self.gaus_img, axes=dict(x=1,y=0)) #, axes=dict(x=1,y=0))
            
            
            if not hasattr(self, 'iso_curve'):
                self.iso_curve = pg.IsocurveItem(data=self.gaus_img, level=0.5)#, pen, axisOrder)
                self.imview_roi.getView().addItem(self.iso_curve)
            else:
                print(height*0.5)
                self.iso_curve.setData(data=self.gaus_img.T, level=height*0.5)
                self.iso_curve.setParentItem(self.imview_roi.getImageItem())



#From https://gist.github.com/andrewgiessel/6122739
import scipy.optimize

def gaussian(height, center_x, center_y, width_x, width_y, rotation):
    """Returns a gaussian function with the given parameters"""
    width_x = float(width_x)
    width_y = float(width_y)

    rotation = np.deg2rad(rotation)<commit_msg>gauss2d_fit_img: calculate fwhm in info display<commit_after>from ScopeFoundry.data_browser import DataBrowser, DataBrowserView
import pyqtgraph as pg
import numpy as np
from scipy.misc import imread
import os
import pyqtgraph.dockarea
from qtpy import QtCore, QtWidgets
from pyqtgraph.graphicsItems.ROI import EllipseROI


class Gauss2DFitImgView(DataBrowserView):

    name = 'gauss2d_fit_img'
    
    def setup(self):
        
        self.ui = self.dockarea = pyqtgraph.dockarea.DockArea()
        self.imview = pg.ImageView()
        self.imview.getView().invertY(True) # uper left origin
        self.dockarea.addDock(name='Full Image', widget=self.imview)

        self.imview_roi = pg.ImageView()
        self.imview_roi.getView().invertY(True) # upper left origin
        self.dockarea.addDock(name='ROI Image', widget=self.imview_roi)

        self.imview_gauss = pg.ImageView()
        self.imview_gauss.getView().invertY(True) # upper left origin
        self.dockarea.addDock(name='Gauss Fit Image', widget=self.imview_gauss)
        
        
        self.rect_roi = pg.RectROI([20, 20], [100, 100], pen=(0,9))
        self.imview.getView().addItem(self.rect_roi)        
        self.rect_roi.sigRegionChanged[object].connect(self.on_change_rect_roi)

        self.info_label = QtWidgets.QLabel()
        self.dockarea.addDock(name='info', widget=self.info_label)

        
    def on_change_data_filename(self, fname):
        
        try:
            self.data = imread(fname)
            if len(self.data.shape) == 3:
                self.data = self.data.sum(axis=2)
                
            self.imview.setImage(self.data, axes=dict(x=1,y=0))
        except Exception as err:
            self.imview.setImage(np.zeros((10,10)))
            self.databrowser.ui.statusbar.showMessage("failed to load %s:\n%s" %(fname, err))
            raise(err)

        self.on_change_rect_roi()

        
    def is_file_supported(self, fname):
        _, ext = os.path.splitext(fname)
        return ext.lower() in ['.png', '.tif', '.tiff', '.jpg']


    def on_change_rect_roi(self, roi=None):
        # pyqtgraph axes are x,y, but data is stored in (frame, y,x, time)
        #roi_slice, roi_tr = self.rect_roi.getArraySlice(self.data, self.imview.getImageItem(), axes=(1,0))
        #self.rect_plotdata.setData(self.spec_x_array, self.hyperspec_data[roi_slice].mean(axis=(0,1))+1)
        
        self.roi_img = self.rect_roi.getArrayRegion(data=self.data, img=self.imview.getImageItem(), axes=(1,0)) 
        
        #print(self.roi_img.shape)
        
        self.imview_roi .setImage(self.roi_img, axes=dict(x=1,y=0)) #, axes=dict(x=1,y=0))
        #print("roi_slice", roi_slice)
        
        p,success = fitgaussian(self.roi_img)
        
        height, x, y, width_x, width_y, angle = p
        print(p)
        
        if success:
            
            fwhm_x = 2*np.sqrt(2*np.log(2)) * width_x
            fwhm_y = 2*np.sqrt(2*np.log(2)) * width_y
            
            self.info_label.setText(
                "height:{}, x: {}, y: {}, width_x: {}, width_y: {}, angle: {}".format(*p) +
                "\nfwhm {} {}".format(fwhm_x, fwhm_y)
                )
            
            ny,nx = self.roi_img.shape
            X,Y = np.mgrid[:ny,:nx]
            self.gaus_img = gaussian(*p)(X,Y)
            
            self.imview_gauss.setImage(self.gaus_img, axes=dict(x=1,y=0)) #, axes=dict(x=1,y=0))
            
            
            if not hasattr(self, 'iso_curve'):
                self.iso_curve = pg.IsocurveItem(data=self.gaus_img, level=0.5)#, pen, axisOrder)
                self.imview_roi.getView().addItem(self.iso_curve)
            else:
                print(height*0.5)
                self.iso_curve.setData(data=self.gaus_img.T, level=height*0.5)
                self.iso_curve.setParentItem(self.imview_roi.getImageItem())



#From https://gist.github.com/andrewgiessel/6122739
import scipy.optimize

def gaussian(height, center_x, center_y, width_x, width_y, rotation):
    """Returns a gaussian function with the given parameters"""
    width_x = float(width_x)
    width_y = float(width_y)

    rotation = np.deg2rad(rotation)
{'fraction_non_alphanumeric': 0.13039203637704314, 'fraction_numerical': 0.013395600344107165, 'mean_word_length': 2.4050209205020923, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3920564', 'n_tokens_mistral': 2975, 'n_tokens_neox': 2842, 'n_words': 450}