<commit_before>import wx
import sys
from wx.lib.scrolledpanel import ScrolledPanel
from sas.sasgui.guiframe.events import PlotQrangeEvent
from sas.sasgui.guiframe.events import StatusEvent
from sas.sasgui.guiframe.panel_base import PanelBase
from sas.sasgui.guiframe.utils import check_float
from sas.sasgui.guiframe.dataFitting import Data1D
from sas.sasgui.perspectives.invariant.invariant_widgets import OutputTextCtrl
from sas.sasgui.perspectives.invariant.invariant_widgets import InvTextCtrl
from sas.sasgui.perspectives.fitting.basepage import ModelTextCtrl
from sas.sasgui.perspectives.corfunc.corfunc_state import CorfuncState
import sas.sasgui.perspectives.corfunc.corfunc
from sas.sascalc.corfunc.corfunc_calculator import CorfuncCalculator

OUTPUT_STRINGS = {
    'max': "Long Period (A): ",
    'Lc': "Average Hard Block Thickness (A): ",
    'dtr': "Average Interface Thickness (A): ",
    'd0': "Average Core Thickness: ",
    'A': "PolyDispersity: ",
    'fill': "Filling Fraction: "
}

if sys.platform.count("win32") > 0:
    _STATICBOX_WIDTH = 350
    PANEL_WIDTH = 400
    PANEL_HEIGHT = 700
    FONT_VARIANT = 0
else:
    _STATICBOX_WIDTH = 390
    PANEL_WIDTH = 430
    PANEL_HEIGHT = 700
    FONT_VARIANT = 1

class CorfuncPanel(ScrolledPanel,PanelBase):
    window_name = "Correlation Function"
    window_caption = "Correlation Function"
    CENTER_PANE = True

    def __init__(self, parent, data=None, manager=None, *args, **kwds):
        kwds["size"] = (PANEL_WIDTH, PANEL_HEIGHT)
        kwds["style"] = wx.FULL_REPAINT_ON_RESIZE
        ScrolledPanel.__init__(self, parent=parent, *args, **kwds)
        PanelBase.__init__(self, parent)
        self.SetupScrolling()
        self.SetWindowVariant(variant=FONT_VARIANT)
        self._manager = manager
        # The data with no correction for background values
        self._data = data # The data to be analysed (corrected fr background)
        self._extrapolated_data = None # The extrapolated data set
        self._transformed_data = None # Fourier trans. of the extrapolated data
        self._calculator = CorfuncCalculator()
        self._data_name_box = None # Text box to show name of file
        self._background_input = None
        self._qmin_input = None
        self._qmax1_input = None
        self._qmax2_input = None
        self._transform_btn = None
        self._extract_btn = None
        self.qmin = 0
        self.qmax = (0, 0)
        self.background = 0
        self.extracted_params = None
        # Dictionary for saving refs to text boxes used to display output data
        self._output_boxes = None
        self.state = None
        self._do_layout()
        self._disable_inputs()
        self.set_state()
        self._qmin_input.Bind(wx.EVT_TEXT, self._on_enter_input)
        self._qmax1_input.Bind(wx.EVT_TEXT, self._on_enter_input)
        self._qmax2_input.Bind(wx.EVT_TEXT, self._on_enter_input)
        self._qmin_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
        self._qmax1_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
        self._qmax2_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
        self._background_input.Bind(wx.EVT_TEXT, self._on_enter_input)

    def set_state(self, state=None, data=None):
        """
        Set the state of the panel. If no state is provided, the panel will
        be set to the default state.

        :param state: A CorfuncState object
        :param data: A Data1D object
        """
        if state is None:
            self.state = CorfuncState()
        else:
            self.state = state
        if data is not None:
            self.state.data = data
        self.set_data(data, set_qrange=False)
        if self.state.qmin is not None:
            self.set_qmin(self.state.qmin)
        if self.state.qmax is not None and self.state.qmax != (None, None):
            self.set_qmax(tuple(self.state.qmax))
        if self.state.background is not None:
            self.set_background(self.state.background)
        if self.state.is_extrapolated:
            self.compute_extrapolation()
        else:
            return
        if self.state.is_transformed:
            self.compute_transform()
        else:
            return
        if self.state.outputs is not None and self.state.outputs != {}:
            self.set_extracted_params(self.state.outputs)

    def get_state(self):
        """
        Return the state of the panel
        """
        state = CorfuncState()
        state.set_saved_state('qmin_tcl', self.qmin)
        state.set_saved_state('qmax1_tcl', self.qmax[0])
        state.set_saved_state('qmax2_tcl', self.qmax[1])
        state.set_saved_state('background_tcl', self.background)
        state.outputs = self.extracted_params
        if self._data is not None:
            state.file = self._data.title
            state.data = self._data
        if self._extrapolated_data is not None:
            state.is_extrapolated = True
        if self._transformed_data is not None:
            state.is_transformed = True
        self.state = state

        return self.state

    def onSetFocus(self, evt):
        if evt is not None:
            evt.Skip()
        self._validate_inputs()

    def set_data(self, data=None, set_qrange=True):
        """
        Update the GUI to reflect new data that has been loaded in

        :param data: The data that has been loaded
        """
        if data is None:
            return
        self._enable_inputs()
        self._transform_btn.Disable()
        self._extract_btn.Disable()
        self._data_name_box.SetValue(str(data.title))
        self._data = data
        self._calculator.set_data(data)
        # Reset the outputs
        self.set_extracted_params(None)
        if self._manager is not None:
            from sas.sasgui.perspectives.corfunc.corfunc import IQ_DATA_LABEL
            self._manager.clear_data()
            self._manager.show_data(self._data, IQ_DATA_LABEL, reset=True)

        if set_qrange:
            lower = data.x[-1]*0.05
            upper1 = data.x[-1] - lower*5
            upper2 = data.x[-1]
            self.set_qmin(lower)
            self.set_qmax((upper1, upper2))
            self.set_background(self._calculator.compute_background(self.qmax))

    def get_data(self):
        return self._data

    def compute_extrapolation(self, event=None):
        """
        Compute and plot the extrapolated data.
        Called when Extrapolate button is pressed.
        """
        if not self._validate_inputs:
            msg = "Invalid Q range entered."
            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
            return
        self._calculator.set_data(self._data)
        self._calculator.lowerq = self.qmin
        self._calculator.upperq = self.qmax
        self._calculator.background = self.background
        try:
            self._extrapolated_data = self._calculator.compute_extrapolation()
        except:
            msg = "Error extrapolating data."
            wx.PostEvent(self._manager.parent,
                StatusEvent(status=msg, info="Error"))
            self._transform_btn.Disable()
            return
        # TODO: Find way to set xlim and ylim so full range of data can be
        # plotted
        maxq = self._data.x.max()
        mask = self._extrapolated_data.x <= maxq
        numpts = len(self._extrapolated_data.x[mask]) + 250
        plot_x = self._extrapolated_data.x[0:numpts]
        plot_y = self._extrapolated_data.y[0:numpts]
        to_plot = Data1D(plot_x, plot_y)
        from sas.sasgui.perspectives.corfunc.corfunc import\
            IQ_EXTRAPOLATED_DATA_LABEL
        self._manager.show_data(to_plot, IQ_EXTRAPOLATED_DATA_LABEL)
        self._transform_btn.Enable()

    def compute_transform(self, event=None):
        """
        Compute and plot the transformed data.
        Called when Transform button is pressed.
        """
        try:
            transformed_data = self._calculator.compute_transform(
                self._extrapolated_data, self.background)
        except:
            transformed_data = None
        if transformed_data is None:
            msg = "Error calculating Transform."
            wx.PostEvent(self._manager.parent,
                StatusEvent(status=msg, info="Error"))
            self._extract_btn.Disable()
            return
        self._transformed_data = transformed_data
        from sas.sasgui.perspectives.corfunc.corfunc import TRANSFORM_LABEL
        import numpy as np
        plot_x = transformed_data.x[np.where(transformed_data.x <= 200)]
        plot_y = transformed_data.y[np.where(transformed_data.x <= 200)]
        self._manager.show_data(Data1D(plot_x, plot_y), TRANSFORM_LABEL)
        self._extract_btn.Enable()

    def extract_parameters(self, event=None):
        try:
            params = self._calculator.extract_parameters(self._transformed_data)
        except:
            params = None
        if params is None:
            msg = "Error extracting parameters."
            wx.PostEvent(self._manager.parent,
                StatusEvent(status=msg, info="Error"))
            return
        self.set_extracted_params(params)

    def save_project(self, doc=None):
        """
        Return an XML node containing the state of the panel

        :param doc: Am xml node to attach the project state to (optional)
        """
        data = self._data
        state = self.get_state()
        if data is not None:
            import pdb; pdb.set_trace()
            new_doc, sasentry = self._manager.state_reader._to_xml_doc(data)
            new_doc = state.toXML(doc=new_doc, entry_node=sasentry)
            if new_doc is not None:
                if doc is not None and hasattr(doc, "firstChild"):
                    child = new_doc.getElementsByTagName("SASentry")
                    for item in child:
                        doc.firstChild.appendChild(item)
                else:
                    doc = new_doc
        return doc

    def set_qmin(self, qmin):
        self.qmin = qmin
        self._qmin_input.SetValue(str(qmin))

    def set_qmax(self, qmax):
        self.qmax = qmax
        self._qmax1_input.SetValue(str(qmax[0]))
        self._qmax2_input.SetValue(str(qmax[1]))

    def set_background(self, bg):
        self.background = bg
        self._background_input.SetValue(str(bg))
        self._calculator.background = bg

    def set_extracted_params(self, params):
        self.extracted_params = params
        if params is None:
            for key in OUTPUT_STRINGS.keys():
                self._output_boxes[key].SetValue('-')
        else:<commit_msg>Remove another debug statement<commit_after>import wx
import sys
from wx.lib.scrolledpanel import ScrolledPanel
from sas.sasgui.guiframe.events import PlotQrangeEvent
from sas.sasgui.guiframe.events import StatusEvent
from sas.sasgui.guiframe.panel_base import PanelBase
from sas.sasgui.guiframe.utils import check_float
from sas.sasgui.guiframe.dataFitting import Data1D
from sas.sasgui.perspectives.invariant.invariant_widgets import OutputTextCtrl
from sas.sasgui.perspectives.invariant.invariant_widgets import InvTextCtrl
from sas.sasgui.perspectives.fitting.basepage import ModelTextCtrl
from sas.sasgui.perspectives.corfunc.corfunc_state import CorfuncState
import sas.sasgui.perspectives.corfunc.corfunc
from sas.sascalc.corfunc.corfunc_calculator import CorfuncCalculator

OUTPUT_STRINGS = {
    'max': "Long Period (A): ",
    'Lc': "Average Hard Block Thickness (A): ",
    'dtr': "Average Interface Thickness (A): ",
    'd0': "Average Core Thickness: ",
    'A': "PolyDispersity: ",
    'fill': "Filling Fraction: "
}

if sys.platform.count("win32") > 0:
    _STATICBOX_WIDTH = 350
    PANEL_WIDTH = 400
    PANEL_HEIGHT = 700
    FONT_VARIANT = 0
else:
    _STATICBOX_WIDTH = 390
    PANEL_WIDTH = 430
    PANEL_HEIGHT = 700
    FONT_VARIANT = 1

class CorfuncPanel(ScrolledPanel,PanelBase):
    window_name = "Correlation Function"
    window_caption = "Correlation Function"
    CENTER_PANE = True

    def __init__(self, parent, data=None, manager=None, *args, **kwds):
        kwds["size"] = (PANEL_WIDTH, PANEL_HEIGHT)
        kwds["style"] = wx.FULL_REPAINT_ON_RESIZE
        ScrolledPanel.__init__(self, parent=parent, *args, **kwds)
        PanelBase.__init__(self, parent)
        self.SetupScrolling()
        self.SetWindowVariant(variant=FONT_VARIANT)
        self._manager = manager
        # The data with no correction for background values
        self._data = data # The data to be analysed (corrected fr background)
        self._extrapolated_data = None # The extrapolated data set
        self._transformed_data = None # Fourier trans. of the extrapolated data
        self._calculator = CorfuncCalculator()
        self._data_name_box = None # Text box to show name of file
        self._background_input = None
        self._qmin_input = None
        self._qmax1_input = None
        self._qmax2_input = None
        self._transform_btn = None
        self._extract_btn = None
        self.qmin = 0
        self.qmax = (0, 0)
        self.background = 0
        self.extracted_params = None
        # Dictionary for saving refs to text boxes used to display output data
        self._output_boxes = None
        self.state = None
        self._do_layout()
        self._disable_inputs()
        self.set_state()
        self._qmin_input.Bind(wx.EVT_TEXT, self._on_enter_input)
        self._qmax1_input.Bind(wx.EVT_TEXT, self._on_enter_input)
        self._qmax2_input.Bind(wx.EVT_TEXT, self._on_enter_input)
        self._qmin_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
        self._qmax1_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
        self._qmax2_input.Bind(wx.EVT_MOUSE_EVENTS, self._on_click_qrange)
        self._background_input.Bind(wx.EVT_TEXT, self._on_enter_input)

    def set_state(self, state=None, data=None):
        """
        Set the state of the panel. If no state is provided, the panel will
        be set to the default state.

        :param state: A CorfuncState object
        :param data: A Data1D object
        """
        if state is None:
            self.state = CorfuncState()
        else:
            self.state = state
        if data is not None:
            self.state.data = data
        self.set_data(data, set_qrange=False)
        if self.state.qmin is not None:
            self.set_qmin(self.state.qmin)
        if self.state.qmax is not None and self.state.qmax != (None, None):
            self.set_qmax(tuple(self.state.qmax))
        if self.state.background is not None:
            self.set_background(self.state.background)
        if self.state.is_extrapolated:
            self.compute_extrapolation()
        else:
            return
        if self.state.is_transformed:
            self.compute_transform()
        else:
            return
        if self.state.outputs is not None and self.state.outputs != {}:
            self.set_extracted_params(self.state.outputs)

    def get_state(self):
        """
        Return the state of the panel
        """
        state = CorfuncState()
        state.set_saved_state('qmin_tcl', self.qmin)
        state.set_saved_state('qmax1_tcl', self.qmax[0])
        state.set_saved_state('qmax2_tcl', self.qmax[1])
        state.set_saved_state('background_tcl', self.background)
        state.outputs = self.extracted_params
        if self._data is not None:
            state.file = self._data.title
            state.data = self._data
        if self._extrapolated_data is not None:
            state.is_extrapolated = True
        if self._transformed_data is not None:
            state.is_transformed = True
        self.state = state

        return self.state

    def onSetFocus(self, evt):
        if evt is not None:
            evt.Skip()
        self._validate_inputs()

    def set_data(self, data=None, set_qrange=True):
        """
        Update the GUI to reflect new data that has been loaded in

        :param data: The data that has been loaded
        """
        if data is None:
            return
        self._enable_inputs()
        self._transform_btn.Disable()
        self._extract_btn.Disable()
        self._data_name_box.SetValue(str(data.title))
        self._data = data
        self._calculator.set_data(data)
        # Reset the outputs
        self.set_extracted_params(None)
        if self._manager is not None:
            from sas.sasgui.perspectives.corfunc.corfunc import IQ_DATA_LABEL
            self._manager.clear_data()
            self._manager.show_data(self._data, IQ_DATA_LABEL, reset=True)

        if set_qrange:
            lower = data.x[-1]*0.05
            upper1 = data.x[-1] - lower*5
            upper2 = data.x[-1]
            self.set_qmin(lower)
            self.set_qmax((upper1, upper2))
            self.set_background(self._calculator.compute_background(self.qmax))

    def get_data(self):
        return self._data

    def compute_extrapolation(self, event=None):
        """
        Compute and plot the extrapolated data.
        Called when Extrapolate button is pressed.
        """
        if not self._validate_inputs:
            msg = "Invalid Q range entered."
            wx.PostEvent(self.parent.parent, StatusEvent(status=msg))
            return
        self._calculator.set_data(self._data)
        self._calculator.lowerq = self.qmin
        self._calculator.upperq = self.qmax
        self._calculator.background = self.background
        try:
            self._extrapolated_data = self._calculator.compute_extrapolation()
        except:
            msg = "Error extrapolating data."
            wx.PostEvent(self._manager.parent,
                StatusEvent(status=msg, info="Error"))
            self._transform_btn.Disable()
            return
        # TODO: Find way to set xlim and ylim so full range of data can be
        # plotted
        maxq = self._data.x.max()
        mask = self._extrapolated_data.x <= maxq
        numpts = len(self._extrapolated_data.x[mask]) + 250
        plot_x = self._extrapolated_data.x[0:numpts]
        plot_y = self._extrapolated_data.y[0:numpts]
        to_plot = Data1D(plot_x, plot_y)
        from sas.sasgui.perspectives.corfunc.corfunc import\
            IQ_EXTRAPOLATED_DATA_LABEL
        self._manager.show_data(to_plot, IQ_EXTRAPOLATED_DATA_LABEL)
        self._transform_btn.Enable()

    def compute_transform(self, event=None):
        """
        Compute and plot the transformed data.
        Called when Transform button is pressed.
        """
        try:
            transformed_data = self._calculator.compute_transform(
                self._extrapolated_data, self.background)
        except:
            transformed_data = None
        if transformed_data is None:
            msg = "Error calculating Transform."
            wx.PostEvent(self._manager.parent,
                StatusEvent(status=msg, info="Error"))
            self._extract_btn.Disable()
            return
        self._transformed_data = transformed_data
        from sas.sasgui.perspectives.corfunc.corfunc import TRANSFORM_LABEL
        import numpy as np
        plot_x = transformed_data.x[np.where(transformed_data.x <= 200)]
        plot_y = transformed_data.y[np.where(transformed_data.x <= 200)]
        self._manager.show_data(Data1D(plot_x, plot_y), TRANSFORM_LABEL)
        self._extract_btn.Enable()

    def extract_parameters(self, event=None):
        try:
            params = self._calculator.extract_parameters(self._transformed_data)
        except:
            params = None
        if params is None:
            msg = "Error extracting parameters."
            wx.PostEvent(self._manager.parent,
                StatusEvent(status=msg, info="Error"))
            return
        self.set_extracted_params(params)

    def save_project(self, doc=None):
        """
        Return an XML node containing the state of the panel

        :param doc: Am xml node to attach the project state to (optional)
        """
        data = self._data
        state = self.get_state()
        if data is not None
            new_doc, sasentry = self._manager.state_reader._to_xml_doc(data)
            new_doc = state.toXML(doc=new_doc, entry_node=sasentry)
            if new_doc is not None:
                if doc is not None and hasattr(doc, "firstChild"):
                    child = new_doc.getElementsByTagName("SASentry")
                    for item in child:
                        doc.firstChild.appendChild(item)
                else:
                    doc = new_doc
        return doc

    def set_qmin(self, qmin):
        self.qmin = qmin
        self._qmin_input.SetValue(str(qmin))

    def set_qmax(self, qmax):
        self.qmax = qmax
        self._qmax1_input.SetValue(str(qmax[0]))
        self._qmax2_input.SetValue(str(qmax[1]))

    def set_background(self, bg):
        self.background = bg
        self._background_input.SetValue(str(bg))
        self._calculator.background = bg

    def set_extracted_params(self, params):
        self.extracted_params = params
        if params is None:
            for key in OUTPUT_STRINGS.keys():
                self._output_boxes[key].SetValue('-')
        else:
{'fraction_non_alphanumeric': 0.08727323996616224, 'fraction_numerical': 0.006391578155841715, 'mean_word_length': 2.2858245830759727, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, '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': '250675', 'n_tokens_mistral': 6582, 'n_tokens_neox': 6337, 'n_words': 1417}