class BackrubProteinSim_PropertyManager(Command_PropertyManager):
    """
    The BackrubProteinSim_PropertyManager class provides a Property Manager
    for the B{Fixed backbone Protein Sequence Design} command on the flyout toolbar in the
    Build > Protein > Simulate mode.

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title = "Backrub Motion"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildProtein/Backrub.png"

    def __init__(self, command):
        """
        Constructor for the property manager.
        """
        _superclass.__init__(self, command)
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        msg = "Choose various parameters from below to design an optimized" \
            " protein sequence with Rosetta with backrub motion allowed."
        self.updateMessage(msg)

    def connect_or_disconnect_signals(self, isConnect=True):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.ex1Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex1)
        change_connect(self.ex1aroCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_ex1aro)
        change_connect(self.ex2Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex2)
        change_connect(self.ex2aroOnlyCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_ex2aro_only)
        change_connect(self.ex3Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex3)
        change_connect(self.ex4Checkbox, SIGNAL("stateChanged(int)"),
                       self.update_ex4)
        change_connect(self.rotOptCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_rot_opt)
        change_connect(self.tryBothHisTautomersCheckbox,
                       SIGNAL("stateChanged(int)"),
                       self.update_try_both_his_tautomers)
        change_connect(self.softRepDesignCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_soft_rep_design)
        change_connect(self.useElecRepCheckbox, SIGNAL("stateChanged(int)"),
                       self.update_use_elec_rep)
        change_connect(self.norepackDisulfCheckbox,
                       SIGNAL("stateChanged(int)"),
                       self.update_norepack_disulf)
        #signal slot connections for the push buttons
        change_connect(self.okButton, SIGNAL("clicked()"),
                       self.runRosettaBackrubSim)
        return

    #Protein Display methods

    def show(self):
        """
        Shows the Property Manager. Exends superclass method.
        """
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()
        #update the min and max residues spinbox max values based on the length
        #of the current protein
        numResidues = self._getNumResiduesForCurrentProtein()
        if numResidues == 0:
            self.minresSpinBox.setMaximum(numResidues + 2)
            self.maxresSpinBox.setMaximum(numResidues + 2)
        else:
            self.minresSpinBox.setMaximum(numResidues)
            self.maxresSpinBox.setMaximum(numResidues)

        _superclass.show(self)

        return

    def _addGroupBoxes(self):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox2 = PM_GroupBox(self,
                                        title="Backrub Specific Parameters")
        self._loadGroupBox2(self._pmGroupBox2)

        self._pmGroupBox1 = PM_GroupBox(
            self, title="Rosetta Sequence Design Parameters")
        self._loadGroupBox1(self._pmGroupBox1)

        return

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        self.bondAngleWeightSimSpinBox = PM_DoubleSpinBox(
            pmGroupBox,
            labelColumn=0,
            label="Bond angle weight:",
            minimum=0.01,
            decimals=2,
            maximum=1.0,
            singleStep=0.01,
            value=1.0,
            setAsDefault=False,
            spanWidth=False)

        bond_angle_param_list = ['Amber', 'Charmm']

        self.bondAngleParamComboBox = PM_ComboBox(
            pmGroupBox,
            label="Bond angle parameters:",
            choices=bond_angle_param_list,
            setAsDefault=False)

        self.onlybbSpinBox = PM_DoubleSpinBox(pmGroupBox,
                                              labelColumn=0,
                                              label="Only backbone rotation:",
                                              minimum=0.01,
                                              maximum=1.0,
                                              value=0.75,
                                              decimals=2,
                                              singleStep=0.01,
                                              setAsDefault=False,
                                              spanWidth=False)

        self.onlyrotSpinBox = PM_DoubleSpinBox(pmGroupBox,
                                               labelColumn=0,
                                               label="Only rotamer rotation:",
                                               minimum=0.01,
                                               maximum=1.0,
                                               decimals=2,
                                               value=0.25,
                                               singleStep=0.01,
                                               setAsDefault=False,
                                               spanWidth=False)

        self.mctempSpinBox = PM_DoubleSpinBox(
            pmGroupBox,
            labelColumn=0,
            label="MC simulation temperature:",
            minimum=0.1,
            value=0.6,
            maximum=1.0,
            decimals=2,
            singleStep=0.1,
            setAsDefault=False,
            spanWidth=False)

        numResidues = self._getNumResiduesForCurrentProtein()
        self.minresSpinBox = PM_SpinBox(pmGroupBox,
                                        labelColumn=0,
                                        label="Minimum number of residues:",
                                        minimum=2,
                                        maximum=numResidues,
                                        singleStep=1,
                                        setAsDefault=False,
                                        spanWidth=False)

        self.maxresSpinBox = PM_SpinBox(pmGroupBox,
                                        labelColumn=0,
                                        label="Maximum number of residues:",
                                        minimum=2,
                                        maximum=numResidues,
                                        singleStep=1,
                                        setAsDefault=False,
                                        spanWidth=False)
        if numResidues == 0:
            self.minresSpinBox.setMaximum(numResidues + 2)
            self.maxresSpinBox.setMaximum(numResidues + 2)
        return

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.
        """
        pass

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.
        """
        pass

    def _getNumResiduesForCurrentProtein(self):
        """
        Get number of residues for the current protein
        """
        _current_protein = self.win.assy.getSelectedProteinChunk()
        if _current_protein:
            return len(_current_protein.protein.get_sequence_string())
        return 0

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """

        self.numSimSpinBox = PM_SpinBox(pmGroupBox,
                                        labelColumn=0,
                                        label="Number of trials:",
                                        minimum=1000,
                                        maximum=1000000,
                                        singleStep=1000,
                                        setAsDefault=False,
                                        spanWidth=False)

        self.ex1Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi1 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex1aroCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use large chi1 library for aromatic residues",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex2Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi2 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex2aroOnlyCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use large chi2 library only for aromatic residues",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex3Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi3 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.ex4Checkbox = PM_CheckBox(
            pmGroupBox,
            text="Expand rotamer library for chi4 angle",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.rotOptCheckbox = PM_CheckBox(pmGroupBox,
                                          text="Optimize one-body energy",
                                          state=Qt.Unchecked,
                                          setAsDefault=False,
                                          widgetColumn=0,
                                          spanWidth=True)

        self.tryBothHisTautomersCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Try both histidine tautomers",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.softRepDesignCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use softer Lennard-Jones repulsive term",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.useElecRepCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Use electrostatic repulsion",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.norepackDisulfCheckbox = PM_CheckBox(
            pmGroupBox,
            text="Don't re-pack disulphide bonds",
            state=Qt.Unchecked,
            setAsDefault=False,
            widgetColumn=0,
            spanWidth=True)

        self.otherCommandLineOptions = PM_TextEdit(
            pmGroupBox, label="Command line options:", spanWidth=True)
        self.otherCommandLineOptions.setFixedHeight(80)

        self.okButton = PM_PushButton(pmGroupBox,
                                      text="Run Rosetta",
                                      setAsDefault=True,
                                      spanWidth=True)
        return

    def update_ex1(self, state):
        """
        Update the command text edit depending on the state of the update_ex1
        checkbox
        @param state:state of the update_ex1 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex1aro(self, state):
        """
        Update the command text edit depending on the state of the update_ex1aro
        checkbox
        @param state:state of the update_ex1aro checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1aroCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1aro '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1aro ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex2(self, state):
        """
        Update the command text edit depending on the state of the update_ex2
        checkbox
        @param state:state of the update_ex2 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex2aro_only(self, state):
        """
        Update the command text edit depending on the state of the update_ex2aro_only
        checkbox
        @param state:state of the update_ex2aro_only checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2aroOnlyCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2aro_only '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2aro_only ', '')

        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex3(self, state):
        """
        Update the command text edit depending on the state of the update_ex3
        checkbox
        @param state:state of the update_ex3 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex3Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex3 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex3 ', '')

        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_ex4(self, state):
        """
        Update the command text edit depending on the state of the update_ex4
        checkbox
        @param state:state of the update_ex4 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex4Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex4 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex4 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_rot_opt(self, state):
        """
        Update the command text edit depending on the state of the update_rot_opt
        checkbox
        @param state:state of the update_rot_opt checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.rotOptCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -rot_opt '
        else:
            otherOptionsText = otherOptionsText.replace(' -rot_opt ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_try_both_his_tautomers(self, state):
        """
        Update the command text edit depending on the state of the update_try_both_his_tautomers
        checkbox
        @param state:state of the update_try_both_his_tautomers checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.tryBothHisTautomersCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -try_both_his_tautomers '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -try_both_his_tautomers ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_soft_rep_design(self, state):
        """
        Update the command text edit depending on the state of the update_soft_rep_design
        checkbox
        @param state:state of the update_soft_rep_design checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.softRepDesignCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -soft_rep_design '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -soft_rep_design ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_use_elec_rep(self, state):
        """
        Update the command text edit depending on the state of the update_use_elec_rep
        checkbox
        @param state:state of the update_use_elec_rep checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.useElecRepCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -use_electrostatic_repulsion '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -use_electrostatic_repulsion ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def update_norepack_disulf(self, state):
        """
        Update the command text edit depending on the state of the update_no_repack
        checkbox
        @param state:state of the update_no_repack checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.norepackDisulfCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -norepack_disulf '
        else:
            otherOptionsText = otherOptionsText.replace(
                ' -norepack_disulf ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)
        return

    def runRosettaBackrubSim(self):
        """
        Get all the parameters from the PM and run a rosetta simulation
        """
        proteinChunk = self.win.assy.getSelectedProteinChunk()
        if not proteinChunk:
            msg = "You must select a single protein to run a Rosetta <i>Backrub</i> simulation."
            self.updateMessage(msg)
            return
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        numSim = self.numSimSpinBox.value()
        argList = [numSim, otherOptionsText, proteinChunk.name]
        backrubSpecificArgList = self.getBackrubSpecificArgumentList()
        from simulation.ROSETTA.rosetta_commandruns import rosettaSetup_CommandRun
        if argList[0] > 0:
            env.prefs[rosetta_backrub_enabled_prefs_key] = True
            cmdrun = rosettaSetup_CommandRun(
                self.win, argList, "BACKRUB_PROTEIN_SEQUENCE_DESIGN",
                backrubSpecificArgList)
            cmdrun.run()
        return

    def getBackrubSpecificArgumentList(self):
        """
        get list of backrub specific parameters from PM
        """
        listOfArgs = []

        bond_angle_weight = str(self.bondAngleWeightSimSpinBox.value())
        listOfArgs.append('-bond_angle_weight')
        listOfArgs.append(bond_angle_weight)

        if self.bondAngleParamComboBox.currentIndex() == 0:
            bond_angle_params = 'bond_angle_amber_rosetta'
        else:
            bond_angle_params = 'bond_angle_charmm_rosetta'

        listOfArgs.append('-bond_angle_params')
        listOfArgs.append(bond_angle_params)

        only_bb = str(self.onlybbSpinBox.value())
        listOfArgs.append('-only_bb')
        listOfArgs.append(only_bb)

        only_rot = str(self.onlyrotSpinBox.value())
        listOfArgs.append('-only_rot')
        listOfArgs.append(only_rot)

        mc_temp = str(self.mctempSpinBox.value())
        listOfArgs.append('-mc_temp')
        listOfArgs.append(mc_temp)

        min_res = self.minresSpinBox.value()
        max_res = self.maxresSpinBox.value()
        if max_res < min_res:
            msg = redmsg("Maximum number of residues for rosetta simulation with backrub" \
                " motion cannot be less than minimum number of residues."\
                " Neglecting this parameter for this simulation.")

            env.history.message("BACKRUB SIMULATION: " + msg)
        else:
            listOfArgs.append('-min_res')
            listOfArgs.append(str(min_res))
            listOfArgs.append('-max_res')
            listOfArgs.append(str(max_res))

        return listOfArgs
class InsertPeptide_PropertyManager(EditCommand_PM):
    """
    The InsertPeptide_PropertyManager class provides a Property Manager 
    for the "Insert > Peptide" command.
    """
    # The title that appears in the property manager header.
    title = "Insert Peptide"
    # The name of this property manager. This will be set to
    # the name of the PropMgr (this) object via setObjectName().
    pmName = title
    # The relative path to PNG file that appears in the header.
    iconPath = "ui/actions/Command Toolbar/BuildProtein/InsertPeptide.png"

    # phi psi angles will define the secondary structure of the peptide chain
    phi = -57.0
    psi = -47.0
    chirality = 1
    secondary = SS_HELIX
    current_amino_acid = 7  # Glycine

    # DEPRECATED ATTRS
    #peptide_cache = []
    #peptide_cache.append((0, 0, 0))

    def __init__(self, command):
        """
        Construct the Property Manager.
        """
        _superclass.__init__(self, command)


        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_CANCEL_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        return

    def show(self):
        """
        Extends superclass method.
        """
        _superclass.show(self)
        self.updateMessage("Choose the peptide parameters below, then click "\
                           "two endpoints in the graphics area to insert a "\
                           "peptide chain.")
        return

    def getParameters(self):
        """
        Return the parameters from this property manager
        to be used to create the  peptide.
        @return: A tuple containing the parameters
        @rtype: tuple
        @see: L{InsertPeptide_EditCommand._gatherParameters()} where this is used        
        """
        return (self.secondary, self.phi, self.psi, self.current_amino_acid)

    def _addGroupBoxes(self):
        """
        Add the group boxe to the Peptide Property Manager dialog.
        """
        self.pmGroupBox1 = \
            PM_GroupBox( self,
                         title          = "Peptide Parameters" )

        # Add group box widgets.
        self._loadGroupBox1(self.pmGroupBox1)
        return

    def _loadGroupBox1(self, inPmGroupBox):
        """
        Load widgets in the group box.
        """

        memberChoices = [
            "Custom", "Alpha helix", "Beta strand", "Pi helix", "3_10 helix",
            "Polyproline-II helix", "Fully extended"
        ]

        self.aaTypeComboBox= \
            PM_ComboBox( inPmGroupBox,
                         label        = "Conformation:",
                         choices      = memberChoices,
                         index        = 1,
                         setAsDefault = True,
                         spanWidth    = False )

        self.connect(self.aaTypeComboBox, SIGNAL("currentIndexChanged(int)"),
                     self._aaTypeChanged)

        self.phiAngleField = \
            PM_DoubleSpinBox( inPmGroupBox,
                              label        = "Phi angle:",
                              value        = self.phi,
                              setAsDefault = True,
                              minimum      = -180.0,
                              maximum      = 180.0,
                              singleStep   = 1.0,
                              decimals     = 1,
                              suffix       = " degrees")

        self.connect(self.phiAngleField, SIGNAL("valueChanged(double)"),
                     self._aaPhiAngleChanged)

        self.phiAngleField.setEnabled(False)

        self.psiAngleField = \
            PM_DoubleSpinBox( inPmGroupBox,
                              label        = "Psi angle:",
                              value        = self.psi,
                              setAsDefault = True,
                              minimum      = -180.0,
                              maximum      = 180.0,
                              singleStep   = 1.0,
                              decimals     = 1,
                              suffix       = " degrees" )

        self.connect(self.psiAngleField, SIGNAL("valueChanged(double)"),
                     self._aaPsiAngleChanged)

        self.psiAngleField.setEnabled(False)

        self.aaTypesButtonGroup = \
            PM_ToolButtonGrid( inPmGroupBox,
                               buttonList   = AA_BUTTON_LIST,
                               label        = "Amino acids",
                               checkedId    = self.current_amino_acid, # Glycine
                               setAsDefault = True )

        self.connect(self.aaTypesButtonGroup.buttonGroup,
                     SIGNAL("buttonClicked(int)"), self._setAminoAcidType)
        return

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.  
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_InsertPeptide_PropertyManager
        whatsThis_InsertPeptide_PropertyManager(self)
        return

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_InsertPeptide_PropertyManager
        ToolTip_InsertPeptide_PropertyManager(self)
        return

    def _aaChiralityChanged(self):
        """
        Set chirality of the peptide chain. 
        """

        # This feature is currently disable as it was confusing to the users
        # who expected control over chirality of amino acids (D/L conformers)
        # rather than over polypeptide chain (left/right-handed structure).

        self.psi *= -1
        self.phi *= -1

        self.phiAngleField.setValue(self.phi)
        self.psiAngleField.setValue(self.psi)
        return

    def _aaTypeChanged(self, idx):
        """
        Slot for Peptide Structure Type combo box. Changes phi/psi angles 
        for secondary structure.
        
        @param idx: index of secondary structure combo box
        @type idx: int
        """
        self.ss_idx = idx

        if idx == 0:
            self.phiAngleField.setEnabled(True)
            self.psiAngleField.setEnabled(True)
        else:
            self.phiAngleField.setEnabled(False)
            self.psiAngleField.setEnabled(False)

        if idx == 1:  # alpha helix
            self.phi = -57.0
            self.psi = -47.0
            self.secondary = SS_HELIX
        elif idx == 2:  # beta strand
            self.phi = -135.0
            self.psi = 135.0
            self.secondary = SS_STRAND
        elif idx == 3:  # 3-10 helix
            self.phi = -55.0
            self.psi = -70.0
            self.secondary = SS_HELIX
        elif idx == 4:  # pi helix
            self.phi = -49.0
            self.psi = -26.0
            self.secondary = SS_HELIX
        elif idx == 5:  # polyprolin-II
            self.phi = -75.0
            self.psi = 150.0
            self.secondary = SS_COIL
        elif idx == 6:  # fully extended
            self.phi = -180.0
            self.psi = 180.0
            self.secondary = SS_STRAND
        else:
            self.phi = self.phiAngleField.value()
            self.psi = self.psiAngleField.value()
            self.secondary = SS_COIL

        self.phi *= self.chirality
        self.psi *= self.chirality

        self.command.secondary = self.secondary

        self.phiAngleField.setValue(self.phi)
        self.psiAngleField.setValue(self.psi)
        return

    def _aaPhiAngleChanged(self, phi):
        """
        Called when phi angle spin box has changed. 
        
        @param phi: phi angle value
        @type phi: float
        """
        self.phi = self.phiAngleField.value()
        return

    def _aaPsiAngleChanged(self, psi):
        """
        Called when psi angle spin box has changed. 
        
        @param psi: psi angle value
        @type psi: float
        """
        self.psi = self.psiAngleField.value()
        return

    def _setAminoAcidType(self, index):
        """
        Sets the current amino acid type to I{index}.
        """
        self.current_amino_acid = index
        return

    # --------------------------------------------------------------------
    # Deprecated methods to keep until we're certain this is working.
    # --Mark 2008-12-12.

    def addAminoAcid_DEPRECATED(self, index):
        """
        Adds a new amino acid to the peptide molecule.        
        """

        # This commened out code is obsolete in interactive peptide builder.
        # The interactive peptide builder creates homopeptides.

        # add a new amino acid and chain conformation to the peptide cache
        #self.peptide_cache.append((index,self.phi,self.psi))
        #self.peptide_cache[0] = (index,self.phi,self.psi)

        self.current_amino_acid = index
        return

    def _setAminoAcidType_DEPRECATED(self, aaTypeIndex):
        """
        Adds a new amino acid to the peptide molecule.
        """
        # piotr 080911: this method is obsolete as of 080911. It was used in
        # the old Peptide Generator.
        button, idx, short_name, dum, name, symbol, x, y = AA_BUTTON_LIST[
            aaTypeIndex]
        if self.ss_idx == 1:
            aa_txt = "<font color=red>"
        elif self.ss_idx == 2:
            aa_txt = "<font color=blue>"
        elif self.ss_idx == 3:
            aa_txt = "<font color=green>"
        elif self.ss_idx == 4:
            aa_txt = "<font color=orange>"
        elif self.ss_idx == 5:
            aa_txt = "<font color=magenta>"
        elif self.ss_idx == 6:
            aa_txt = "<font color=darkblue>"
        else:
            aa_txt = "<font color=black>"

        aa_txt += symbol + "</font>"
        #self.sequenceEditor.insertHtml(aa_txt, False, 4, 10, False)
        return
Пример #3
0
class InsertDna_PropertyManager(DnaOrCnt_PropertyManager):
    """
    The InsertDna_PropertyManager class provides a Property Manager
    for the B{Insert Dna} command.

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title = "Insert DNA"
    pmName = title
    iconPath = "ui/actions/Command Toolbar/BuildDna/InsertDna.png"

    def __init__(self, command):
        """
        Constructor for the DNA Duplex property manager.
        """
        self.endPoint1 = None
        self.endPoint2 = None

        self._conformation = "B-DNA"
        self._numberOfBases = 0
        self._basesPerTurn = getDuplexBasesPerTurn(self._conformation)
        self._duplexRise = getDuplexRise(self._conformation)
        self._duplexLength = getDuplexLength(self._conformation,
                                             self._numberOfBases)

        _superclass.__init__(self, command)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_CANCEL_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self._placementOptions.buttonGroup,
                       SIGNAL("buttonClicked(int)"),
                       self.activateSpecifyReferencePlaneTool)

        change_connect(self.conformationComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.conformationComboBoxChanged)

        change_connect(self.numberOfBasePairsSpinBox,
                       SIGNAL("valueChanged(int)"), self.numberOfBasesChanged)

        change_connect(self.basesPerTurnDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.basesPerTurnChanged)

        change_connect(self.duplexRiseDoubleSpinBox,
                       SIGNAL("valueChanged(double)"), self.duplexRiseChanged)

        change_connect(self.showCursorTextCheckBox,
                       SIGNAL('stateChanged(int)'),
                       self._update_state_of_cursorTextGroupBox)

        self.duplexRiseDoubleSpinBox.connectWithState(
            Preferences_StateRef_double(bdnaRise_prefs_key,
                                        env.prefs[bdnaRise_prefs_key]))

        self.basesPerTurnDoubleSpinBox.connectWithState(
            Preferences_StateRef_double(bdnaBasesPerTurn_prefs_key,
                                        env.prefs[bdnaBasesPerTurn_prefs_key]))

    def show(self):
        _superclass.show(self)
        self.updateMessage("Specify the DNA parameters below, then click "\
                           "two endpoints in the graphics area to insert a DNA duplex.")

    def _addGroupBoxes(self):
        """
        Add the DNA Property Manager group boxes.
        """
        self._pmReferencePlaneGroupBox = PM_GroupBox(self,
                                                     title="Placement Options")
        self._loadReferencePlaneGroupBox(self._pmReferencePlaneGroupBox)

        self._pmGroupBox1 = PM_GroupBox(self, title="Endpoints")
        self._loadGroupBox1(self._pmGroupBox1)

        self._pmGroupBox1.hide()

        self._pmGroupBox2 = PM_GroupBox(self, title="Parameters")
        self._loadGroupBox2(self._pmGroupBox2)

        self._displayOptionsGroupBox = PM_GroupBox(self,
                                                   title="Display Options")
        self._loadDisplayOptionsGroupBox(self._displayOptionsGroupBox)

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box 3.
        """
        #Folllowing toolbutton facilitates entering a temporary DnaLineMode
        #to create a DNA using endpoints of the specified line.
        self.specifyDnaLineButton = PM_ToolButton(
            pmGroupBox,
            text="Specify Endpoints",
            iconPath="ui/actions/Properties Manager/Pencil.png",
            spanWidth=True)
        self.specifyDnaLineButton.setCheckable(True)
        self.specifyDnaLineButton.setAutoRaise(True)
        self.specifyDnaLineButton.setToolButtonStyle(
            Qt.ToolButtonTextBesideIcon)

        #EndPoint1 and endPoint2 coordinates. These widgets are hidden
        # as of 2007- 12 - 05
        self._endPoint1SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox,
                                                          label="End Point 1")
        self.x1SpinBox = self._endPoint1SpinBoxes.xSpinBox
        self.y1SpinBox = self._endPoint1SpinBoxes.ySpinBox
        self.z1SpinBox = self._endPoint1SpinBoxes.zSpinBox

        self._endPoint2SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox,
                                                          label="End Point 2")
        self.x2SpinBox = self._endPoint2SpinBoxes.xSpinBox
        self.y2SpinBox = self._endPoint2SpinBoxes.ySpinBox
        self.z2SpinBox = self._endPoint2SpinBoxes.zSpinBox

        self._endPoint1SpinBoxes.hide()
        self._endPoint2SpinBoxes.hide()

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box 4.
        """

        self.conformationComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Conformation:",
                         choices       =  ["B-DNA"],
                         setAsDefault  =  True)

        dnaModelChoices = ['PAM3', 'PAM5']
        self.dnaModelComboBox = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Model:",
                         choices       =  dnaModelChoices,
                         setAsDefault  =  True)


        self.basesPerTurnDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Bases per turn:",
                              value         =  env.prefs[bdnaBasesPerTurn_prefs_key],
                              setAsDefault  =  True,
                              minimum       =  8.0,
                              maximum       =  20.0,
                              decimals      =  2,
                              singleStep    =  0.1 )


        self.duplexRiseDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Rise:",
                              value         =  env.prefs[bdnaRise_prefs_key],
                              setAsDefault  =  True,
                              minimum       =  2.0,
                              maximum       =  4.0,
                              decimals      =  3,
                              singleStep    =  0.01 )

        # Strand Length (i.e. the number of bases)
        self.numberOfBasePairsSpinBox = \
            PM_SpinBox( pmGroupBox,
                        label         =  "Base pairs:",
                        value         =  self._numberOfBases,
                        setAsDefault  =  False,
                        minimum       =  0,
                        maximum       =  10000 )

        self.numberOfBasePairsSpinBox.setDisabled(True)

        # Duplex Length
        self.duplexLengthLineEdit  =  \
            PM_LineEdit( pmGroupBox,
                         label         =  "Duplex length: ",
                         text          =  "0.0 Angstroms",
                         setAsDefault  =  False)

        self.duplexLengthLineEdit.setDisabled(True)

    def _loadDisplayOptionsGroupBox(self, pmGroupBox):
        """
        Load widgets in the Display Options GroupBox
        @see: DnaOrCnt_PropertyManager. _loadDisplayOptionsGroupBox
        """
        #Call the superclass method that loads the cursor text checkboxes.
        #Note, as of 2008-05-19, the superclass, DnaOrCnt_PropertyManager
        #only loads the cursor text groupboxes. Subclasses like this can
        #call custom methods like self._loadCursorTextCheckBoxes etc if they
        #don't need all groupboxes that the superclass loads.
        _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox)

        self._rubberbandLineGroupBox = PM_GroupBox(pmGroupBox,
                                                   title='Rubber band line:')

        dnaLineChoices = ['Ribbons', 'Ladder']
        self.dnaRubberBandLineDisplayComboBox = \
            PM_ComboBox( self._rubberbandLineGroupBox ,
                         label         =  " Display as:",
                         choices       =  dnaLineChoices,
                         setAsDefault  =  True)

        self.lineSnapCheckBox = \
            PM_CheckBox(self._rubberbandLineGroupBox ,
                        text         = 'Enable line snap' ,
                        widgetColumn = 1,
                        state        = Qt.Checked
                    )

    def _connect_showCursorTextCheckBox(self):
        """
        Connect the show cursor text checkbox with user prefs_key.
        Overrides
        DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox
        """
        connect_checkbox_with_boolean_pref(
            self.showCursorTextCheckBox,
            dnaDuplexEditCommand_showCursorTextCheckBox_prefs_key)

    def _params_for_creating_cursorTextCheckBoxes(self):
        """
        Returns params needed to create various cursor text checkboxes connected
        to prefs_keys  that allow custom cursor texts.
        @return: A list containing tuples in the following format:
                ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes
                uses this data to create checkboxes with the the given names and
                connects them to the provided preference keys. (Note that
                PM_PrefsCheckBoxes puts thes within a GroupBox)
        @rtype: list
        @see: PM_PrefsCheckBoxes
        @see: self._loadDisplayOptionsGroupBox where this list is used.
        @see: Superclass method which is overridden here --
        DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes()
        """
        params = \
        [  #Format: (" checkbox text", prefs_key)
            ("Number of base pairs",
             dnaDuplexEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key),

            ("Number of turns",
             dnaDuplexEditCommand_cursorTextCheckBox_numberOfTurns_prefs_key),

            ("Duplex length",
             dnaDuplexEditCommand_cursorTextCheckBox_length_prefs_key),

            ("Angle",
             dnaDuplexEditCommand_cursorTextCheckBox_angle_prefs_key) ]

        return params

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.
        """
        pass

    def conformationComboBoxChanged(self, inIndex):
        """
        Slot for the Conformation combobox. It is called whenever the
        Conformation choice is changed.

        @param inIndex: The new index.
        @type  inIndex: int
        """
        conformation = self.conformationComboBox.currentText()

        if conformation == "B-DNA":
            self.basesPerTurnDoubleSpinBox.setValue("10.0")

        elif conformation == "Z-DNA":
            self.basesPerTurnDoubleSpinBox.setValue("12.0")

        else:
            msg = redmsg("conformationComboBoxChanged(): \
                         Error - unknown DNA conformation. Index = " + inIndex)
            env.history.message(msg)

        self.duplexLengthSpinBox.setSingleStep(getDuplexRise(conformation))

    def numberOfBasesChanged(self, numberOfBases):
        """
        Slot for the B{Number of Bases} spinbox.
        """
        # Update the Duplex Length lineEdit widget.
        text = str(getDuplexLength(self._conformation,
                                   numberOfBases,
                                   self._duplexRise)) \
             + " Angstroms"
        self.duplexLengthLineEdit.setText(text)
        return

    def basesPerTurnChanged(self, basesPerTurn):
        """
        Slot for the B{Bases per turn} spinbox.
        """
        self.command.basesPerTurn = basesPerTurn
        self._basesPerTurn = basesPerTurn
        return

    def duplexRiseChanged(self, rise):
        """
        Slot for the B{Rise} spinbox.
        """
        self.command.duplexRise = rise
        self._duplexRise = rise
        return

    def getParameters(self):
        """
        Return the parameters from this property manager
        to be used to create the DNA duplex.
        @return: A tuple containing the parameters
        @rtype: tuple
        @see: L{InsertDna_EditCommand._gatherParameters} where this is used
        """
        numberOfBases = self.numberOfBasePairsSpinBox.value()
        dnaForm = str(self.conformationComboBox.currentText())
        basesPerTurn = self.basesPerTurnDoubleSpinBox.value()
        duplexRise = self.duplexRiseDoubleSpinBox.value()

        dnaModel = str(self.dnaModelComboBox.currentText())

        # First endpoint (origin) of DNA duplex
        x1 = self.x1SpinBox.value()
        y1 = self.y1SpinBox.value()
        z1 = self.z1SpinBox.value()

        # Second endpoint (direction vector/axis) of DNA duplex.
        x2 = self.x2SpinBox.value()
        y2 = self.y2SpinBox.value()
        z2 = self.z2SpinBox.value()

        if not self.endPoint1:
            self.endPoint1 = V(x1, y1, z1)
        if not self.endPoint2:
            self.endPoint2 = V(x2, y2, z2)

        return (numberOfBases, dnaForm, dnaModel, basesPerTurn, duplexRise,
                self.endPoint1, self.endPoint2)

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.
        """
        whatsThis_InsertDna_PropertyManager(self)
Пример #4
0
class BackrubProteinSim_PropertyManager(Command_PropertyManager):
    """
    The BackrubProteinSim_PropertyManager class provides a Property Manager 
    for the B{Fixed backbone Protein Sequence Design} command on the flyout toolbar in the 
    Build > Protein > Simulate mode. 

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Backrub Motion"
    pmName        =  title
    iconPath      = "ui/actions/Command Toolbar/BuildProtein/Backrub.png"

    
    def __init__( self, command ):
        """
        Constructor for the property manager.
        """                  
        _superclass.__init__(self, command)
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        msg = "Choose various parameters from below to design an optimized" \
            " protein sequence with Rosetta with backrub motion allowed."
        self.updateMessage(msg)
        
    def connect_or_disconnect_signals(self, isConnect = True):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot 
                          method. 
        @type  isConnect: boolean
        """
        
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect 
        
        change_connect(self.ex1Checkbox, SIGNAL("stateChanged(int)"), self.update_ex1)
        change_connect(self.ex1aroCheckbox, SIGNAL("stateChanged(int)"), self.update_ex1aro)
        change_connect(self.ex2Checkbox, SIGNAL("stateChanged(int)"), self.update_ex2)
        change_connect(self.ex2aroOnlyCheckbox, SIGNAL("stateChanged(int)"), self.update_ex2aro_only)
        change_connect(self.ex3Checkbox, SIGNAL("stateChanged(int)"), self.update_ex3)
        change_connect(self.ex4Checkbox, SIGNAL("stateChanged(int)"), self.update_ex4)
        change_connect(self.rotOptCheckbox, SIGNAL("stateChanged(int)"), self.update_rot_opt)
        change_connect(self.tryBothHisTautomersCheckbox, SIGNAL("stateChanged(int)"), self.update_try_both_his_tautomers)
        change_connect(self.softRepDesignCheckbox, SIGNAL("stateChanged(int)"), self.update_soft_rep_design)
        change_connect(self.useElecRepCheckbox, SIGNAL("stateChanged(int)"), self.update_use_elec_rep)
        change_connect(self.norepackDisulfCheckbox, SIGNAL("stateChanged(int)"), self.update_norepack_disulf)
        #signal slot connections for the push buttons
        change_connect(self.okButton, SIGNAL("clicked()"), self.runRosettaBackrubSim)
        return
    
    #Protein Display methods         

    def show(self):
        """
        Shows the Property Manager. Exends superclass method. 
        """
        self.sequenceEditor = self.win.createProteinSequenceEditorIfNeeded()
        self.sequenceEditor.hide()
        #update the min and max residues spinbox max values based on the length
        #of the current protein
        numResidues = self._getNumResiduesForCurrentProtein()
        if numResidues == 0:
            self.minresSpinBox.setMaximum(numResidues + 2)
            self.maxresSpinBox.setMaximum(numResidues + 2)
        else:    
            self.minresSpinBox.setMaximum(numResidues)
            self.maxresSpinBox.setMaximum(numResidues)
        
        _superclass.show(self)       
       
        return

    def _addGroupBoxes( self ):
        """
        Add the Property Manager group boxes.
        """
        self._pmGroupBox2 = PM_GroupBox( self,
                                         title = "Backrub Specific Parameters")
        self._loadGroupBox2( self._pmGroupBox2 )
        
        self._pmGroupBox1 = PM_GroupBox( self,
                                         title = "Rosetta Sequence Design Parameters")
        self._loadGroupBox1( self._pmGroupBox1 )
        
        return
    
    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        self.bondAngleWeightSimSpinBox = PM_DoubleSpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Bond angle weight:",
                                         minimum = 0.01,
                                         decimals     = 2, 
                                         maximum = 1.0,
                                         singleStep = 0.01,
                                         value = 1.0,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        bond_angle_param_list = ['Amber', 'Charmm']
        
        self.bondAngleParamComboBox = PM_ComboBox( pmGroupBox,
                                                   label         =  "Bond angle parameters:",
                                                   choices       =  bond_angle_param_list,
                                                   setAsDefault  =  False)
        
        self.onlybbSpinBox = PM_DoubleSpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Only backbone rotation:",
                                         minimum  = 0.01,
                                         maximum  = 1.0,
                                         value    = 0.75, 
                                         decimals = 2, 
                                         singleStep = 0.01,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        self.onlyrotSpinBox = PM_DoubleSpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Only rotamer rotation:",
                                         minimum  = 0.01,
                                         maximum  = 1.0,
                                         decimals = 2, 
                                         value    = 0.25, 
                                         singleStep = 0.01,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        self.mctempSpinBox = PM_DoubleSpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "MC simulation temperature:",
                                         minimum  = 0.1,
                                         value    = 0.6, 
                                         maximum  = 1.0,
                                         decimals = 2, 
                                         singleStep = 0.1,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        numResidues = self._getNumResiduesForCurrentProtein()
        self.minresSpinBox = PM_SpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Minimum number of residues:",
                                         minimum = 2,
                                         maximum = numResidues,
                                         singleStep = 1,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        self.maxresSpinBox = PM_SpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Maximum number of residues:",
                                         minimum = 2,
                                         maximum = numResidues,
                                         singleStep = 1,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        if numResidues == 0:
            self.minresSpinBox.setMaximum(numResidues + 2)
            self.maxresSpinBox.setMaximum(numResidues + 2)
        return
    
    
    def _addWhatsThisText( self ):
        """
        What's This text for widgets in this Property Manager.  
        """
        pass
                
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        pass
    
    def _getNumResiduesForCurrentProtein(self):
        """
        Get number of residues for the current protein
        """
        _current_protein = self.win.assy.getSelectedProteinChunk()
        if _current_protein:
            return len(_current_protein.protein.get_sequence_string())
        return 0
    
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box.
        """
        
        self.numSimSpinBox = PM_SpinBox( pmGroupBox,
                                         labelColumn  = 0,
                                         label = "Number of trials:",
                                         minimum = 1000,
                                         maximum = 1000000,
                                         singleStep = 1000,
                                         setAsDefault  =  False,
                                         spanWidth = False)
        
        self.ex1Checkbox = PM_CheckBox(pmGroupBox,
                                       text = "Expand rotamer library for chi1 angle",
                                       state = Qt.Unchecked,
                                       setAsDefault  =  False,
                                       widgetColumn  = 0,
                                       spanWidth = True)
        
        self.ex1aroCheckbox = PM_CheckBox(pmGroupBox,
                                          text = "Use large chi1 library for aromatic residues",
                                          state = Qt.Unchecked,
                                          setAsDefault  =  False,
                                          widgetColumn  = 0,
                                          spanWidth = True)
        
        self.ex2Checkbox = PM_CheckBox(pmGroupBox,
                                       text = "Expand rotamer library for chi2 angle",
                                       state = Qt.Unchecked,
                                       setAsDefault  =  False,
                                       widgetColumn  = 0,
                                       spanWidth = True)
        
        self.ex2aroOnlyCheckbox = PM_CheckBox(pmGroupBox,
                                              text = "Use large chi2 library only for aromatic residues",
                                              state = Qt.Unchecked,
                                              setAsDefault  =  False,
                                              widgetColumn  = 0,
                                              spanWidth = True)
                                              
        self.ex3Checkbox = PM_CheckBox(pmGroupBox,
                                     text = "Expand rotamer library for chi3 angle",
                                     state = Qt.Unchecked,
                                     setAsDefault  =  False,
                                     widgetColumn  = 0,
                                     spanWidth = True)
        
        self.ex4Checkbox = PM_CheckBox(pmGroupBox,
                                       text ="Expand rotamer library for chi4 angle",
                                       state = Qt.Unchecked,
                                       setAsDefault  =  False,
                                       widgetColumn  = 0,
                                       spanWidth = True)
        
        self.rotOptCheckbox = PM_CheckBox(pmGroupBox,
                                          text ="Optimize one-body energy",
                                          state = Qt.Unchecked,
                                          setAsDefault  =  False,
                                          widgetColumn  = 0,
                                          spanWidth = True)
        
        self.tryBothHisTautomersCheckbox = PM_CheckBox(pmGroupBox,
                                                       text ="Try both histidine tautomers",
                                                       state = Qt.Unchecked,
                                                       setAsDefault  =  False,
                                                       widgetColumn  = 0,
                                                       spanWidth = True)
        
        self.softRepDesignCheckbox = PM_CheckBox(pmGroupBox,
                                                 text ="Use softer Lennard-Jones repulsive term",
                                                 state = Qt.Unchecked,
                                                 setAsDefault  =  False,
                                                 widgetColumn  = 0,
                                                 spanWidth = True)
        
        self.useElecRepCheckbox = PM_CheckBox(pmGroupBox,
                                              text ="Use electrostatic repulsion",
                                              state = Qt.Unchecked,
                                              setAsDefault  =  False,
                                              widgetColumn  = 0,
                                              spanWidth = True)
        
        self.norepackDisulfCheckbox = PM_CheckBox(pmGroupBox,
                                                  text ="Don't re-pack disulphide bonds",
                                                  state = Qt.Unchecked,
                                                  setAsDefault  =  False,
                                                  widgetColumn  = 0,
                                                  spanWidth = True)
        
        
        self.otherCommandLineOptions = PM_TextEdit(pmGroupBox,
                                                   label = "Command line options:",
                                                   spanWidth = True)
        self.otherCommandLineOptions.setFixedHeight(80)
        
        self.okButton = PM_PushButton( pmGroupBox,
                         text         =  "Run Rosetta",
                         setAsDefault  =  True,
                         spanWidth = True)
        return
    
    
    def update_ex1(self, state):
        """
        Update the command text edit depending on the state of the update_ex1
        checkbox
        @param state:state of the update_ex1 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex1aro(self, state):
        """
        Update the command text edit depending on the state of the update_ex1aro
        checkbox
        @param state:state of the update_ex1aro checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex1aroCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex1aro '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex1aro ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex2(self, state):
        """
        Update the command text edit depending on the state of the update_ex2
        checkbox
        @param state:state of the update_ex2 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex2aro_only(self, state):
        """
        Update the command text edit depending on the state of the update_ex2aro_only
        checkbox
        @param state:state of the update_ex2aro_only checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex2aroOnlyCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex2aro_only '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex2aro_only ', '')    
            
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex3(self, state):
        """
        Update the command text edit depending on the state of the update_ex3
        checkbox
        @param state:state of the update_ex3 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex3Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex3 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex3 ', '')
        
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_ex4(self, state):
        """
        Update the command text edit depending on the state of the update_ex4
        checkbox
        @param state:state of the update_ex4 checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.ex4Checkbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -ex4 '
        else:
            otherOptionsText = otherOptionsText.replace(' -ex4 ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_rot_opt(self, state):
        """
        Update the command text edit depending on the state of the update_rot_opt
        checkbox
        @param state:state of the update_rot_opt checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.rotOptCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -rot_opt '
        else:
            otherOptionsText = otherOptionsText.replace(' -rot_opt ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_try_both_his_tautomers(self, state):
        """
        Update the command text edit depending on the state of the update_try_both_his_tautomers
        checkbox
        @param state:state of the update_try_both_his_tautomers checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.tryBothHisTautomersCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -try_both_his_tautomers '
        else:
            otherOptionsText = otherOptionsText.replace(' -try_both_his_tautomers ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_soft_rep_design(self, state):
        """
        Update the command text edit depending on the state of the update_soft_rep_design
        checkbox
        @param state:state of the update_soft_rep_design checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.softRepDesignCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -soft_rep_design '
        else:
            otherOptionsText = otherOptionsText.replace(' -soft_rep_design ', '')
        self.otherCommandLineOptions.setText(otherOptionsText)    
        return
    
    def update_use_elec_rep(self, state):
        """
        Update the command text edit depending on the state of the update_use_elec_rep
        checkbox
        @param state:state of the update_use_elec_rep checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.useElecRepCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -use_electrostatic_repulsion '
        else:
            otherOptionsText = otherOptionsText.replace(' -use_electrostatic_repulsion ', '')    
        self.otherCommandLineOptions.setText(otherOptionsText)        
        return
    
    def update_norepack_disulf(self, state):
        """
        Update the command text edit depending on the state of the update_no_repack
        checkbox
        @param state:state of the update_no_repack checkbox
        @type state: int
        """
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        if self.norepackDisulfCheckbox.isChecked() == True:
            otherOptionsText = otherOptionsText + ' -norepack_disulf '
        else:
            otherOptionsText = otherOptionsText.replace(' -norepack_disulf ', '')      
        self.otherCommandLineOptions.setText(otherOptionsText)        
        return
    
    def runRosettaBackrubSim(self):
        """
        Get all the parameters from the PM and run a rosetta simulation
        """
        proteinChunk = self.win.assy.getSelectedProteinChunk()
        if not proteinChunk:
            msg = "You must select a single protein to run a Rosetta <i>Backrub</i> simulation."
            self.updateMessage(msg)
            return
        otherOptionsText = str(self.otherCommandLineOptions.toPlainText())
        numSim = self.numSimSpinBox.value()
        argList = [numSim, otherOptionsText, proteinChunk.name]
        backrubSpecificArgList = self.getBackrubSpecificArgumentList()
        from simulation.ROSETTA.rosetta_commandruns import rosettaSetup_CommandRun
        if argList[0] > 0:
            env.prefs[rosetta_backrub_enabled_prefs_key] = True
            cmdrun = rosettaSetup_CommandRun(self.win, argList, "BACKRUB_PROTEIN_SEQUENCE_DESIGN", backrubSpecificArgList)
            cmdrun.run() 
        return    
    
    def getBackrubSpecificArgumentList(self):
        """
        get list of backrub specific parameters from PM
        """
        listOfArgs = []
        
        bond_angle_weight = str(self.bondAngleWeightSimSpinBox.value())
        listOfArgs.append('-bond_angle_weight')
        listOfArgs.append( bond_angle_weight)
        
        if self.bondAngleParamComboBox.currentIndex() == 0:
            bond_angle_params = 'bond_angle_amber_rosetta'
        else:
            bond_angle_params = 'bond_angle_charmm_rosetta'
            
        listOfArgs.append('-bond_angle_params')            
        listOfArgs.append(bond_angle_params)    
        
        only_bb = str(self.onlybbSpinBox.value())
        listOfArgs.append('-only_bb')
        listOfArgs.append( only_bb)
        
        only_rot = str(self.onlyrotSpinBox.value())
        listOfArgs.append('-only_rot')
        listOfArgs.append( only_rot)
        
        mc_temp = str(self.mctempSpinBox.value())
        listOfArgs.append('-mc_temp')
        listOfArgs.append( mc_temp)
        
        min_res = self.minresSpinBox.value()
        max_res = self.maxresSpinBox.value()
        if max_res < min_res:
            msg = redmsg("Maximum number of residues for rosetta simulation with backrub" \
                " motion cannot be less than minimum number of residues."\
                " Neglecting this parameter for this simulation.")
            
            env.history.message("BACKRUB SIMULATION: " + msg)
        else:
            listOfArgs.append('-min_res')
            listOfArgs.append( str(min_res))
            listOfArgs.append('-max_res')
            listOfArgs.append( str(max_res))
        
        return listOfArgs
Пример #5
0
class PlanePropertyManager(EditCommand_PM):
    """
    The PlanePropertyManager class provides a Property Manager for a
    (reference) Plane.

    """

    # The title that appears in the Property Manager header.
    title = "Plane"
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to the PNG file that appears in the header
    iconPath = "ui/actions/Insert/Reference Geometry/Plane.png"

    def __init__(self, command):
        """
        Construct the Plane Property Manager.

        @param plane: The plane.
        @type  plane: L{Plane}
        """

        #see self.connect_or_disconnect_signals for comment about this flag
        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False

        self.gridColor = black
        self.gridXSpacing = 4.0
        self.gridYSpacing = 4.0
        self.gridLineType = 3
        self.displayLabels = False
        self.originLocation = PLANE_ORIGIN_LOWER_LEFT
        self.displayLabelStyle = LABELS_ALONG_ORIGIN

        EditCommand_PM.__init__(self, command)

        # Hide Preview and Restore defaults buttons
        self.hideTopRowButtons(PM_RESTORE_DEFAULTS_BUTTON)

    def _addGroupBoxes(self):
        """
        Add the 1st group box to the Property Manager.
        """
        # Placement Options radio button list to create radio button list.
        # Format: buttonId, buttonText, tooltip
        PLACEMENT_OPTIONS_BUTTON_LIST = [ \
            ( 0, "Parallel to screen",     "Parallel to screen"     ),
            ( 1, "Through selected atoms", "Through selected atoms" ),
            ( 2, "Offset to a plane",      "Offset to a plane"      ),
            ( 3, "Custom",                 "Custom"                 )
        ]

        self.pmPlacementOptions = \
            PM_RadioButtonList( self,
                                title      = "Placement Options",
                                buttonList = PLACEMENT_OPTIONS_BUTTON_LIST,
                                checkedId  = 3 )

        self.pmGroupBox1 = PM_GroupBox(self, title="Parameters")
        self._loadGroupBox1(self.pmGroupBox1)

        #image groupbox
        self.pmGroupBox2 = PM_GroupBox(self, title="Image")
        self._loadGroupBox2(self.pmGroupBox2)

        #grid plane groupbox
        self.pmGroupBox3 = PM_GroupBox(self, title="Grid")
        self._loadGroupBox3(self.pmGroupBox3)

    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in the grid plane group box.

        @param pmGroupBox: The grid  group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """
        self.gridPlaneCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Show grid",
                         widgetColumn  = 0,
                         setAsDefault = True,
                         spanWidth = True
                         )

        connect_checkbox_with_boolean_pref(self.gridPlaneCheckBox,
                                           PlanePM_showGrid_prefs_key)


        self.gpXSpacingDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "X Spacing:",
                              value         =  4.000,
                              setAsDefault  =  True,
                              minimum       =  1.00,
                              maximum       =  200.0,
                              decimals      =  3,
                              singleStep    =  1.0,
                              spanWidth = False)

        self.gpYSpacingDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Y Spacing:",
                              value         =  4.000,
                              setAsDefault  =  True,
                              minimum       =  1.00,
                              maximum       =  200.0,
                              decimals      =  3,
                              singleStep    =  1.0,
                              spanWidth = False)

        lineTypeChoices = ['Dotted (default)', 'Dashed', 'Solid']

        self.gpLineTypeComboBox = \
            PM_ComboBox( pmGroupBox ,
                         label         =  "Line type:",
                         choices       =  lineTypeChoices,
                         setAsDefault  =  True)

        hhColorList = [
            black, orange, red, magenta, cyan, blue, white, yellow, gray
        ]
        hhColorNames = [
            "Black (default)", "Orange", "Red", "Magenta", "Cyan", "Blue",
            "White", "Yellow", "Other color..."
        ]

        self.gpColorTypeComboBox = \
            PM_ColorComboBox( pmGroupBox,
                              colorList = hhColorList,
                              colorNames = hhColorNames,
                              color = black )

        self.pmGroupBox5 = PM_GroupBox(pmGroupBox)

        self.gpDisplayLabels =\
            PM_CheckBox( self.pmGroupBox5,
                         text         = "Display labels",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True )

        originChoices = [
            'Lower left (default)', 'Upper left', 'Lower right', 'Upper right'
        ]

        self.gpOriginComboBox = \
            PM_ComboBox( self.pmGroupBox5 ,
                         label         =  "Origin:",
                         choices       =  originChoices,
                         setAsDefault  =  True )

        positionChoices = ['Origin axes (default)', 'Plane perimeter']

        self.gpPositionComboBox = \
            PM_ComboBox( self.pmGroupBox5 ,
                         label         =  "Position:",
                         choices       =  positionChoices,
                         setAsDefault  =  True)

        self._showHideGPWidgets()

        if env.prefs[PlanePM_showGridLabels_prefs_key]:
            self.displayLabels = True
            self.gpOriginComboBox.setEnabled(True)
            self.gpPositionComboBox.setEnabled(True)
        else:
            self.displayLabels = False
            self.gpOriginComboBox.setEnabled(False)
            self.gpPositionComboBox.setEnabled(False)

        return

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """
        #TODO: Fix for bug: When you invoke a temporary mode
        # entering such a temporary mode keeps the signals of
        #PM from the previous mode connected (
        #but while exiting that temporary mode and reentering the
        #previous mode, it actually reconnects the signal! This gives rise to
        #lots  of bugs. This needs more general fix in Temporary mode API.
        # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py

        #UPDATE: (comment copied and modifief from BuildNanotube_PropertyManager.
        #The general problem still remains -- Ninad 2008-06-25

        if isConnect and self.isAlreadyConnected:
            if debug_flags.atom_debug:
                print_compact_stack("warning: attempt to connect widgets"\
                                    "in this PM that are already connected." )
            return

        if not isConnect and self.isAlreadyDisconnected:
            if debug_flags.atom_debug:
                print_compact_stack("warning: attempt to disconnect widgets"\
                                    "in this PM that are already disconnected.")
            return

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.pmPlacementOptions.buttonGroup,
                       SIGNAL("buttonClicked(int)"), self.changePlanePlacement)

        change_connect(self.widthDblSpinBox, SIGNAL("valueChanged(double)"),
                       self.change_plane_width)

        change_connect(self.heightDblSpinBox, SIGNAL("valueChanged(double)"),
                       self.change_plane_height)

        change_connect(self.aspectRatioCheckBox, SIGNAL("stateChanged(int)"),
                       self._enableAspectRatioSpinBox)

        #signal slot connection for imageDisplayCheckBox
        change_connect(self.imageDisplayCheckBox, SIGNAL("stateChanged(int)"),
                       self.toggleFileChooserBehavior)

        #signal slot connection for imageDisplayFileChooser
        change_connect(self.imageDisplayFileChooser.lineEdit,
                       SIGNAL("editingFinished()"), self.update_imageFile)

        #signal slot connection for heightfieldDisplayCheckBox
        change_connect(self.heightfieldDisplayCheckBox,
                       SIGNAL("stateChanged(int)"), self.toggleHeightfield)

        #signal slot connection for heightfieldHQDisplayCheckBox
        change_connect(self.heightfieldHQDisplayCheckBox,
                       SIGNAL("stateChanged(int)"), self.toggleHeightfieldHQ)

        #signal slot connection for heightfieldTextureCheckBox
        change_connect(self.heightfieldTextureCheckBox,
                       SIGNAL("stateChanged(int)"), self.toggleTexture)

        #signal slot connection for vScaleSpinBox
        change_connect(self.vScaleSpinBox, SIGNAL("valueChanged(double)"),
                       self.change_vertical_scale)

        change_connect(self.plusNinetyButton, SIGNAL("clicked()"),
                       self.rotate_90)

        change_connect(self.minusNinetyButton, SIGNAL("clicked()"),
                       self.rotate_neg_90)

        change_connect(self.flipButton, SIGNAL("clicked()"), self.flip_image)

        change_connect(self.mirrorButton, SIGNAL("clicked()"),
                       self.mirror_image)

        change_connect(self.gridPlaneCheckBox, SIGNAL("stateChanged(int)"),
                       self.displayGridPlane)

        change_connect(self.gpXSpacingDoubleSpinBox,
                       SIGNAL("valueChanged(double)"), self.changeXSpacingInGP)

        change_connect(self.gpYSpacingDoubleSpinBox,
                       SIGNAL("valueChanged(double)"), self.changeYSpacingInGP)

        change_connect(self.gpLineTypeComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changeLineTypeInGP)

        change_connect(self.gpColorTypeComboBox, SIGNAL("editingFinished()"),
                       self.changeColorTypeInGP)

        change_connect(self.gpDisplayLabels, SIGNAL("stateChanged(int)"),
                       self.displayLabelsInGP)

        change_connect(self.gpOriginComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changeOriginInGP)

        change_connect(self.gpPositionComboBox,
                       SIGNAL("currentIndexChanged(int)"),
                       self.changePositionInGP)

        self._connect_checkboxes_to_global_prefs_keys()

        return

    def _connect_checkboxes_to_global_prefs_keys(self):
        """
        """
        connect_checkbox_with_boolean_pref(self.gridPlaneCheckBox,
                                           PlanePM_showGrid_prefs_key)

        connect_checkbox_with_boolean_pref(self.gpDisplayLabels,
                                           PlanePM_showGridLabels_prefs_key)

    def changePositionInGP(self, idx):
        """
        Change Display of origin Labels (choices are along origin edges or along
        the plane perimeter.
        @param idx: Current index of the change grid label position combo box
        @type idx: int
        """
        if idx == 0:
            self.displayLabelStyle = LABELS_ALONG_ORIGIN
        elif idx == 1:
            self.displayLabelStyle = LABELS_ALONG_PLANE_EDGES
        else:
            print "Invalid index", idx
        return

    def changeOriginInGP(self, idx):
        """
        Change Display of origin Labels based on the location of the origin
        @param idx: Current index of the change origin position combo box
        @type idx: int
        """
        if idx == 0:
            self.originLocation = PLANE_ORIGIN_LOWER_LEFT
        elif idx == 1:
            self.originLocation = PLANE_ORIGIN_UPPER_LEFT
        elif idx == 2:
            self.originLocation = PLANE_ORIGIN_LOWER_RIGHT
        elif idx == 3:
            self.originLocation = PLANE_ORIGIN_UPPER_RIGHT
        else:
            print "Invalid index", idx
        return

    def displayLabelsInGP(self, state):
        """
        Choose to show or hide grid labels
        @param state: State of the Display Label Checkbox
        @type state: boolean
        """
        if env.prefs[PlanePM_showGridLabels_prefs_key]:
            self.gpOriginComboBox.setEnabled(True)
            self.gpPositionComboBox.setEnabled(True)
            self.displayLabels = True
            self.originLocation = PLANE_ORIGIN_LOWER_LEFT
            self.displayLabelStyle = LABELS_ALONG_ORIGIN
        else:
            self.gpOriginComboBox.setEnabled(False)
            self.gpPositionComboBox.setEnabled(False)
            self.displayLabels = False
        return

    def changeColorTypeInGP(self):
        """
        Change Color of grid
        """
        self.gridColor = self.gpColorTypeComboBox.getColor()
        return

    def changeLineTypeInGP(self, idx):
        """
        Change line type in grid
        @param idx: Current index of the Line type combo box
        @type idx: int
        """
        #line_type for actually drawing the grid is: 0=None, 1=Solid, 2=Dashed" or 3=Dotted
        if idx == 0:
            self.gridLineType = 3
        if idx == 1:
            self.gridLineType = 2
        if idx == 2:
            self.gridLineType = 1
        return

    def changeYSpacingInGP(self, val):
        """
        Change Y spacing on the grid
        @param val:value of Y spacing
        @type val: double
        """
        self.gridYSpacing = float(val)
        return

    def changeXSpacingInGP(self, val):
        """
        Change X spacing on the grid
        @param val:value of X spacing
        @type val: double
        """
        self.gridXSpacing = float(val)
        return

    def displayGridPlane(self, state):
        """
        Display or hide grid based on the state of the checkbox
        @param state: State of the Display Label Checkbox
        @type state: boolean
        """
        self._showHideGPWidgets()
        if self.gridPlaneCheckBox.isChecked():
            env.prefs[PlanePM_showGrid_prefs_key] = True
            self._makeGridPlane()
        else:
            env.prefs[PlanePM_showGrid_prefs_key] = False

        return

    def _makeGridPlane(self):
        """
        Show grid on the plane
        """
        #get all the grid related values in here
        self.gridXSpacing = float(self.gpXSpacingDoubleSpinBox.value())
        self.gridYSpacing = float(self.gpYSpacingDoubleSpinBox.value())

        #line_type for actually drawing the grid is: 0=None, 1=Solid, 2=Dashed" or 3=Dotted
        idx = self.gpLineTypeComboBox.currentIndex()
        self.changeLineTypeInGP(idx)
        self.gridColor = self.gpColorTypeComboBox.getColor()

        return

    def _showHideGPWidgets(self):
        """
        Enable Disable grid related widgets based on the state of the show grid
        checkbox.
        """
        if self.gridPlaneCheckBox.isChecked():
            self.gpXSpacingDoubleSpinBox.setEnabled(True)
            self.gpYSpacingDoubleSpinBox.setEnabled(True)
            self.gpLineTypeComboBox.setEnabled(True)
            self.gpColorTypeComboBox.setEnabled(True)
            self.gpDisplayLabels.setEnabled(True)
        else:
            self.gpXSpacingDoubleSpinBox.setEnabled(False)
            self.gpXSpacingDoubleSpinBox.setEnabled(False)
            self.gpYSpacingDoubleSpinBox.setEnabled(False)
            self.gpLineTypeComboBox.setEnabled(False)
            self.gpColorTypeComboBox.setEnabled(False)
            self.gpDisplayLabels.setEnabled(False)
        return

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in the image group box.

        @param pmGroupBox: The image group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """
        self.imageDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Display image",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.imageDisplayFileChooser = \
            PM_FileChooser(pmGroupBox,
                           label     = 'Image file:',
                           text      = '' ,
                           spanWidth = True,
                           filter    = "PNG (*.png);;"\
                           "All Files (*.*)"
                           )
        self.imageDisplayFileChooser.setEnabled(False)
        # add change image properties button

        BUTTON_LIST = [
            ("QToolButton", 1, "+90",
             "ui/actions/Properties Manager/RotateImage+90.png", "+90", "", 0),
            ("QToolButton", 2, "-90",
             "ui/actions/Properties Manager/RotateImage-90.png", "-90", "", 1),
            ("QToolButton", 3, "FLIP",
             "ui/actions/Properties Manager/FlipImageVertical.png", "Flip", "",
             2),
            ("QToolButton", 4, "MIRROR",
             "ui/actions/Properties Manager/FlipImageHorizontal.png", "Mirror",
             "", 3)
        ]

        #image change button groupbox
        self.pmGroupBox2 = PM_GroupBox(pmGroupBox, title="Modify Image")

        self.imageChangeButtonGroup = \
            PM_ToolButtonRow( self.pmGroupBox2,
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              spanWidth    = True,
                              isAutoRaise  = False,
                              isCheckable  = False,
                              setAsDefault = True,
                              )

        self.imageChangeButtonGroup.buttonGroup.setExclusive(False)

        self.plusNinetyButton = self.imageChangeButtonGroup.getButtonById(1)
        self.minusNinetyButton = self.imageChangeButtonGroup.getButtonById(2)
        self.flipButton = self.imageChangeButtonGroup.getButtonById(3)
        self.mirrorButton = self.imageChangeButtonGroup.getButtonById(4)

        # buttons enabled when a valid image is loaded
        self.mirrorButton.setEnabled(False)
        self.plusNinetyButton.setEnabled(False)
        self.minusNinetyButton.setEnabled(False)
        self.flipButton.setEnabled(False)

        self.heightfieldDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Create 3D relief",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.heightfieldHQDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "High quality",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.heightfieldTextureCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Use texture",
                         widgetColumn  = 0,
                         state        = Qt.Checked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.vScaleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        = " Vertical scale:",
                             value        = 1.0,
                             setAsDefault = True,
                             minimum      = -1000.0, # -1000 A
                             maximum      =  1000.0, # 1000 A
                             singleStep   = 0.1,
                             decimals     = 1,
                             suffix       = ' Angstroms')

        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in 1st group box.

        @param pmGroupBox: The 1st group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """

        self.widthDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        = "Width:",
                             value        = 16.0,
                             setAsDefault = True,
                             minimum      = 1.0,
                             maximum      = 10000.0, # 1000 nm
                             singleStep   = 1.0,
                             decimals     = 1,
                             suffix       = ' Angstroms')



        self.heightDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        =" Height:",
                             value        = 16.0,
                             setAsDefault = True,
                             minimum      = 1.0,
                             maximum      = 10000.0, # 1000 nm
                             singleStep   = 1.0,
                             decimals     = 1,
                             suffix       = ' Angstroms')



        self.aspectRatioCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text         = 'Maintain Aspect Ratio of:' ,
                        widgetColumn = 1,
                        state        = Qt.Unchecked
                        )


        self.aspectRatioSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "",
                              value         =  1.0,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  10.0,
                              singleStep    =  0.1,
                              decimals      =  2,
                              suffix        =  " to 1.00")

        if self.aspectRatioCheckBox.isChecked():
            self.aspectRatioSpinBox.setEnabled(True)
        else:
            self.aspectRatioSpinBox.setEnabled(False)

    def _addWhatsThisText(self):
        """
        What's This text for some of the widgets in this Property Manager.

        @note: Many PM widgets are still missing their "What's This" text.
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PlanePropertyManager
        whatsThis_PlanePropertyManager(self)

    def toggleFileChooserBehavior(self, checked):
        """
        Enables FileChooser and displays image when checkbox is checked otherwise
        not
        """
        self.imageDisplayFileChooser.lineEdit.emit(SIGNAL("editingFinished()"))
        if checked == Qt.Checked:
            self.imageDisplayFileChooser.setEnabled(True)
        elif checked == Qt.Unchecked:
            self.imageDisplayFileChooser.setEnabled(False)
            # if an image is already displayed, that's need to be hidden as well
        else:
            pass

        self.command.struct.glpane.gl_update()

    def toggleHeightfield(self, checked):
        """
        Enables 3D relief drawing mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.display_heightfield = checked
            if checked:
                self.heightfieldHQDisplayCheckBox.setEnabled(True)
                self.heightfieldTextureCheckBox.setEnabled(True)
                self.vScaleSpinBox.setEnabled(True)
                plane.computeHeightfield()
            else:
                self.heightfieldHQDisplayCheckBox.setEnabled(False)
                self.heightfieldTextureCheckBox.setEnabled(False)
                self.vScaleSpinBox.setEnabled(False)
                plane.heightfield = None
            plane.glpane.gl_update()

    def toggleHeightfieldHQ(self, checked):
        """
        Enables high quality rendering in 3D relief mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_hq = checked
            plane.computeHeightfield()
            plane.glpane.gl_update()

    def toggleTexture(self, checked):
        """
        Enables texturing in 3D relief mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_use_texture = checked
            # It is not necessary to re-compute the heightfield coordinates
            # at this point, they are re-computed whenever the "3D relief image"
            # checkbox is set.
            plane.glpane.gl_update()

    def update_spinboxes(self):
        """
        Update the width and height spinboxes.
        @see: Plane.resizeGeometry()
        This typically gets called when the plane is resized from the
        3D workspace (which marks assy as modified) .So, update the spinboxes
        that represent the Plane's width and height, but do no emit 'valueChanged'
        signal when the spinbox value changes.

        @see: Plane.resizeGeometry()
        @see: self._update_UI_do_updates()
        @see: Plane_EditCommand.command_update_internal_state()
        """
        # blockSignals = True make sure that spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().  This is done
        #because the spinbox valu changes as a result of resizing the plane
        #from the 3D workspace.
        if self.command.hasValidStructure():
            self.heightDblSpinBox.setValue(self.command.struct.height,
                                           blockSignals=True)
            self.widthDblSpinBox.setValue(self.command.struct.width,
                                          blockSignals=True)

    def update_imageFile(self):
        """
        Loads image file if path is valid
        """

        # Update buttons and checkboxes.
        self.mirrorButton.setEnabled(False)
        self.plusNinetyButton.setEnabled(False)
        self.minusNinetyButton.setEnabled(False)
        self.flipButton.setEnabled(False)
        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)

        plane = self.command.struct

        # Delete current image and heightfield
        plane.deleteImage()
        plane.heightfield = None
        plane.display_image = self.imageDisplayCheckBox.isChecked()

        if plane.display_image:
            imageFile = str(self.imageDisplayFileChooser.lineEdit.text())

            from model.Plane import checkIfValidImagePath
            validPath = checkIfValidImagePath(imageFile)

            if validPath:
                from PIL import Image

                # Load image from file
                plane.image = Image.open(imageFile)
                plane.loadImage(imageFile)

                # Compute the relief image
                plane.computeHeightfield()

                if plane.image:
                    self.mirrorButton.setEnabled(True)
                    self.plusNinetyButton.setEnabled(True)
                    self.minusNinetyButton.setEnabled(True)
                    self.flipButton.setEnabled(True)
                    self.heightfieldDisplayCheckBox.setEnabled(True)
                    if plane.display_heightfield:
                        self.heightfieldHQDisplayCheckBox.setEnabled(True)
                        self.heightfieldTextureCheckBox.setEnabled(True)
                        self.vScaleSpinBox.setEnabled(True)

    def show(self):
        """
        Show the Plane Property Manager.
        """
        EditCommand_PM.show(self)
        #It turns out that if updateCosmeticProps is called before
        #EditCommand_PM.show, the 'preview' properties are not updated
        #when you are editing an existing plane. Don't know the cause at this
        #time, issue is trivial. So calling it in the end -- Ninad 2007-10-03

        if self.command.struct:

            plane = self.command.struct
            plane.updateCosmeticProps(previewing=True)
            if plane.imagePath:
                self.imageDisplayFileChooser.setText(plane.imagePath)
            self.imageDisplayCheckBox.setChecked(plane.display_image)

            #Make sure that the plane placement option is always set to
            #'Custom' when the Plane PM is shown. This makes sure that bugs like
            #2949 won't occur. Let the user change the plane placement option
            #explicitely
            button = self.pmPlacementOptions.getButtonById(3)
            button.setChecked(True)

    def setParameters(self, params):
        """
        """
        width, height, gridColor, gridLineType, \
             gridXSpacing, gridYSpacing, originLocation, \
             displayLabelStyle = params

        # blockSignals = True  flag makes sure that the
        # spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().
        self.widthDblSpinBox.setValue(width, blockSignals=True)
        self.heightDblSpinBox.setValue(height, blockSignals=True)
        self.win.glpane.gl_update()

        self.gpColorTypeComboBox.setColor(gridColor)
        self.gridLineType = gridLineType

        self.gpXSpacingDoubleSpinBox.setValue(gridXSpacing)
        self.gpYSpacingDoubleSpinBox.setValue(gridYSpacing)

        self.gpOriginComboBox.setCurrentIndex(originLocation)
        self.gpPositionComboBox.setCurrentIndex(displayLabelStyle)

    def getCurrrentDisplayParams(self):
        """
        Returns a tuple containing current display parameters such as current
        image path and grid display params.
        @see: Plane_EditCommand.command_update_internal_state() which uses this
        to decide whether to modify the structure (e.g. because of change in the
        image path or display parameters.)
        """
        imagePath = self.imageDisplayFileChooser.text
        gridColor = self.gpColorTypeComboBox.getColor()

        return (imagePath, gridColor, self.gridLineType, self.gridXSpacing,
                self.gridYSpacing, self.originLocation, self.displayLabelStyle)

    def getParameters(self):
        """
        """
        width = self.widthDblSpinBox.value()
        height = self.heightDblSpinBox.value()
        gridColor = self.gpColorTypeComboBox.getColor()

        params = (width, height, gridColor, self.gridLineType,
                  self.gridXSpacing, self.gridYSpacing, self.originLocation,
                  self.displayLabelStyle)

        return params

    def change_plane_width(self, newWidth):
        """
        Slot for width spinbox in the Property Manager.

        @param newWidth: width in Angstroms.
        @type  newWidth: float
        """
        if self.aspectRatioCheckBox.isChecked():
            self.command.struct.width = newWidth
            self.command.struct.height  =  self.command.struct.width / \
                self.aspectRatioSpinBox.value()
            self.update_spinboxes()
        else:
            self.change_plane_size()
        self._updateAspectRatio()

    def change_plane_height(self, newHeight):
        """
        Slot for height spinbox in the Property Manager.

        @param newHeight: height in Angstroms.
        @type  newHeight: float
        """
        if self.aspectRatioCheckBox.isChecked():
            self.command.struct.height = newHeight
            self.command.struct.width   =  self.command.struct.height * \
                self.aspectRatioSpinBox.value()
            self.update_spinboxes()
        else:
            self.change_plane_size()
        self._updateAspectRatio()

    def change_plane_size(self, gl_update=True):
        """
        Slot to change the Plane's width and height.

        @param gl_update: Forces an update of the glpane.
        @type  gl_update: bool
        """
        self.command.struct.width = self.widthDblSpinBox.value()
        self.command.struct.height = self.heightDblSpinBox.value()
        if gl_update:
            self.command.struct.glpane.gl_update()

    def change_vertical_scale(self, scale):
        """
        Changes vertical scaling of the heightfield.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_scale = scale
            plane.computeHeightfield()
            plane.glpane.gl_update()

    def changePlanePlacement(self, buttonId):
        """
        Slot to change the placement of the plane depending upon the
        option checked in the "Placement Options" group box of the PM.

        @param buttonId: The button id of the selected radio button (option).
        @type  buttonId: int
        """

        if buttonId == 0:
            msg = "Create a Plane parallel to the screen. "\
                "With <b>Parallel to Screen</b> plane placement option, the "\
                "center of the plane is always (0,0,0)"
            self.updateMessage(msg)
            self.command.placePlaneParallelToScreen()
        elif buttonId == 1:
            msg = "Create a Plane with center coinciding with the common center "\
                "of <b> 3 or more selected atoms </b>. If exactly 3 atoms are "\
                "selected, the Plane will pass through those atoms."
            self.updateMessage(msg)
            self.command.placePlaneThroughAtoms()
            if self.command.logMessage:
                env.history.message(self.command.logMessage)
        elif buttonId == 2:
            msg = "Create a Plane at an <b>offset</b> to the selected plane "\
                "indicated by the direction arrow. "\
                "you can click on the direction arrow to reverse its direction."
            self.updateMessage(msg)
            self.command.placePlaneOffsetToAnother()
            if self.command.logMessage:
                env.history.message(self.command.logMessage)
        elif buttonId == 3:
            #'Custom' plane placement. Do nothing (only update message box)
            # Fixes bug 2439
            msg = "Create a plane with a <b>Custom</b> plane placement. "\
                "The plane is placed parallel to the screen, with "\
                "center at (0, 0, 0). User can then modify the plane placement."
            self.updateMessage(msg)

    def _enableAspectRatioSpinBox(self, enable):
        """
        Slot for "Maintain Aspect Ratio" checkbox which enables or disables
        the Aspect Ratio spin box.

        @param enable: True = enable, False = disable.
        @type  enable: bool
        """

        self.aspectRatioSpinBox.setEnabled(enable)

    def _updateAspectRatio(self):
        """
        Updates the Aspect Ratio spin box based on the current width and height.
        """
        aspectRatio = self.command.struct.width / self.command.struct.height
        self.aspectRatioSpinBox.setValue(aspectRatio)

    def _update_UI_do_updates(self):
        """
        Overrides superclass method.
        @see: Command_PropertyManager._update_UI_do_updates() for documentation.

        @see: Plane.resizeGeometry()
        @see: self.update_spinboxes()
        @see: Plane_EditCommand.command_update_internal_state()
        """
        #This typically gets called when the plane is resized from the
        #3D workspace (which marks assy as modified) . So, update the spinboxes
        #that represent the Plane's width and height.
        self.update_spinboxes()

    def update_props_if_needed_before_closing(self):
        """
        This updates some cosmetic properties of the Plane (e.g. fill color,
        border color, etc.) before closing the Property Manager.
        """

        # Example: The Plane Property Manager is open and the user is
        # 'previewing' the plane. Now the user clicks on "Build > Atoms"
        # to invoke the next command (without clicking "Done").
        # This calls openPropertyManager() which replaces the current PM
        # with the Build Atoms PM.  Thus, it creates and inserts the Plane
        # that was being previewed. Before the plane is permanently inserted
        # into the part, it needs to change some of its cosmetic properties
        # (e.g. fill color, border color, etc.) which distinguishes it as
        # a new plane in the part. This function changes those properties.
        # ninad 2007-06-13

        #called in updatePropertyManager in MWsemeantics.py --(Partwindow class)

        EditCommand_PM.update_props_if_needed_before_closing(self)

        #Don't draw the direction arrow when the object is finalized.
        if self.command.struct and \
           self.command.struct.offsetParentGeometry:

            dirArrow = self.command.struct.offsetParentGeometry.directionArrow
            dirArrow.setDrawRequested(False)

    def updateMessage(self, msg=''):
        """
        Updates the message box with an informative message
        @param message: Message to be displayed in the Message groupbox of
                        the property manager
        @type  message: string
        """
        self.MessageGroupBox.insertHtmlMessage(msg,
                                               setAsDefault=False,
                                               minLines=5)

    def rotate_90(self):
        """
        Rotate the image clockwise.
        """
        if self.command.hasValidStructure():
            self.command.struct.rotateImage(0)
        return

    def rotate_neg_90(self):
        """
        Rotate the image counterclockwise.
        """
        if self.command.hasValidStructure():
            self.command.struct.rotateImage(1)
        return

    def flip_image(self):
        """
        Flip the image horizontally.
        """
        if self.command.hasValidStructure():
            self.command.struct.mirrorImage(1)
        return

    def mirror_image(self):
        """
        Flip the image vertically.
        """
        if self.command.hasValidStructure():
            self.command.struct.mirrorImage(0)
        return
class PeptideGeneratorPropertyManager(PM_Dialog):
    """
    The PeptideGeneratorPropertyManager class provides a Property Manager 
    for the "Build > Peptide" command.
    """
    # The title that appears in the property manager header.
    title = "Peptide Generator"
    # The name of this property manager. This will be set to
    # the name of the PropMgr (this) object via setObjectName().
    pmName = title
    # The relative path to PNG file that appears in the header.
    iconPath = "ui/actions/Tools/Build Structures/Peptide.png"

    def __init__(self):
        """Construct the Peptide Property Manager.
        """
        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)

        # phi psi angles will define the secondary structure of the peptide chain
        self.phi = -57.0
        self.psi = -47.0
        self.chirality = 1
        self.ss_idx = 1
        self.peptide_cache = []

        self.updateMessageGroupBox()

    def updateMessageGroupBox(self):
        msg = ""

        msg = msg + "Click on the Amino Acid buttons to add a new residuum to\
            the polypeptide chain. Click <b>Done</b> to insert it into the project."

        # This causes the "Message" box to be displayed as well.
        # setAsDefault=True causes this message to be reset whenever
        # this PropMgr is (re)displayed via show(). Mark 2007-06-01.
        self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=True)

    def _addGroupBoxes(self):
        """
        Add the group boxe to the Peptide Property Manager dialog.
        """
        self.pmGroupBox1 = \
            PM_GroupBox( self, 
                         title          = "Peptide Parameters" )

        # Add group box widgets.
        self._loadGroupBox1(self.pmGroupBox1)

    def _loadGroupBox1(self, inPmGroupBox):
        """
        Load widgets in the group box.
        """

        memberChoices = ["Custom", 
                         "Alpha helix", 
                         "Beta strand",
                         "Pi helix", 
                         "3_10 helix", 
                         "Polyproline-II helix",
                         "Fully extended"]

        self.aaTypeComboBox= \
            PM_ComboBox( inPmGroupBox,
                         label        = "Conformation :", 
                         choices      = memberChoices, 
                         index        = 1, 
                         setAsDefault = True,
                         spanWidth    = False )

        self.connect( self.aaTypeComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self._aaTypeChanged)

        self.phiAngleField = \
            PM_DoubleSpinBox( inPmGroupBox,
                              label        = "Phi angle :", 
                              value        = -57.0, 
                              setAsDefault = True,
                              minimum      = -180.0, 
                              maximum      = 180.0, 
                              singleStep   = 1.0, 
                              decimals     = 1, 
                              suffix       = " degrees")

        self.connect( self.phiAngleField,
                      SIGNAL("valueChanged(double)"),
                      self._aaPhiAngleChanged)

        self.phiAngleField.setEnabled(False)

        self.psiAngleField = \
            PM_DoubleSpinBox( inPmGroupBox,
                              label        = "Psi angle :", 
                              value        = -47.0, 
                              setAsDefault = True,
                              minimum      = -180.0, 
                              maximum      = 180.0, 
                              singleStep   = 1.0, 
                              decimals     = 1, 
                              suffix       = " degrees" )

        self.connect( self.psiAngleField,
                      SIGNAL("valueChanged(double)"),
                      self._aaPsiAngleChanged)

        self.psiAngleField.setEnabled(False)        


        self.invertChiralityPushButton = \
            PM_PushButton( inPmGroupBox,
                           text         = 'Invert chirality' ,
                           spanWidth    = False
                       )

        self.connect(self.invertChiralityPushButton,
                     SIGNAL("clicked()"),
                     self._aaChiralityChanged)

        self.aaTypesButtonGroup = \
            PM_ToolButtonGrid( inPmGroupBox, 
                               buttonList = AA_BUTTON_LIST,
                               label      = "Amino acids :",
                               checkedId  = 0,
                               setAsDefault = True )

        self.connect( self.aaTypesButtonGroup.buttonGroup,
                      SIGNAL("buttonClicked(int)"),
                      self._setAminoAcidType)

        self.sequenceEditor = \
            PM_TextEdit( inPmGroupBox, 
                         label      = "Sequence",
                         spanWidth = True )

        self.sequenceEditor.insertHtml("", False, 4, 10, True)

        self.sequenceEditor.setReadOnly(True)

        self.startOverButton = \
            PM_PushButton( inPmGroupBox,
                           label     = "",
                           text      = "Start Over",
                           spanWidth = True,
                           setAsDefault = True )

        self.connect( self.startOverButton,
                      SIGNAL("clicked()"),
                      self._startOverClicked)

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.  
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PeptideGeneratorPropertyManager
        whatsThis_PeptideGeneratorPropertyManager(self)

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_PeptideGeneratorPropertyManager
        ToolTip_PeptideGeneratorPropertyManager(self)

    def _aaChiralityChanged(self):
        """
        Set chirality of the peptide chain.
        """
        self.psi *= -1
        self.phi *= -1

        self.phiAngleField.setValue(self.phi)
        self.psiAngleField.setValue(self.psi)

    def _aaTypeChanged(self, idx):
        """
        Slot for Peptide Structure Type combobox.
        Changes phi/psi angles for secondary structure.
        """
        self.ss_idx = idx

        if idx == 0:
            self.phiAngleField.setEnabled(True)
            self.psiAngleField.setEnabled(True)
        else:
            self.phiAngleField.setEnabled(False)
            self.psiAngleField.setEnabled(False)

        if idx == 1: # alpha helix
            self.phi = -57.0
            self.psi = -47.0
        elif idx == 2: # beta strand
            self.phi = -135.0
            self.psi = 135.0
        elif idx == 3: # 3-10 helix
            self.phi = -55.0
            self.psi = -70.0
        elif idx == 4: # pi helix
            self.phi = -49.0
            self.psi = -26.0
        elif idx == 5: # polyprolin-II
            self.phi = -75.0
            self.psi = 150.0
        elif idx == 6: # fully extended
            self.phi = -180.0
            self.psi = 180.0
        else:
            self.phi = self.phiAngleField.value()
            self.psi = self.psiAngleField.value()

        self.phi *= self.chirality
        self.psi *= self.chirality

        self.phiAngleField.setValue(self.phi)
        self.psiAngleField.setValue(self.psi)
        pass

    def _aaPhiAngleChanged(self, phi):
        self.phi = self.phiAngleField.value()
        pass


    def _aaPsiAngleChanged(self, psi):
        self.psi = self.psiAngleField.value()
        pass        

    def _setAminoAcidType(self, aaTypeIndex):
        """
        Adds a new amino acid to the peptide molecule.
        """
        button, idx, short_name, dum, name, symbol, x, y = AA_BUTTON_LIST[aaTypeIndex]
        if self.ss_idx==1:
            aa_txt = "<font color=red>"
        elif self.ss_idx==2:
            aa_txt = "<font color=blue>"
        elif self.ss_idx==3:
            aa_txt = "<font color=green>"
        elif self.ss_idx==4:
            aa_txt = "<font color=orange>"
        elif self.ss_idx==5:
            aa_txt = "<font color=magenta>"
        elif self.ss_idx==6:
            aa_txt = "<font color=darkblue>"
        else:
            aa_txt = "<font color=black>"

        aa_txt += symbol+"</font>"
        self.sequenceEditor.insertHtml(aa_txt, False, 4, 10, False)
        self.addAminoAcid(aaTypeIndex)
        pass

    def _startOverClicked(self):
        """
        Resets a sequence in the sequence editor window.
        """
        self.sequenceEditor.clear()
        self.peptide_cache = []
        pass
class PlanePropertyManager(EditCommand_PM):
    """
    The PlanePropertyManager class provides a Property Manager for a
    (reference) Plane.

    """

    # The title that appears in the Property Manager header.
    title = "Plane"
    # The name of this Property Manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to the PNG file that appears in the header
    iconPath = "ui/actions/Insert/Reference Geometry/Plane.png"

    def __init__(self, command):
        """
        Construct the Plane Property Manager.

        @param plane: The plane.
        @type  plane: L{Plane}
        """

        #see self.connect_or_disconnect_signals for comment about this flag
        self.isAlreadyConnected = False
        self.isAlreadyDisconnected = False

        self.gridColor = black
        self.gridXSpacing = 4.0
        self.gridYSpacing = 4.0
        self.gridLineType = 3
        self.displayLabels = False
        self.originLocation = PLANE_ORIGIN_LOWER_LEFT
        self.displayLabelStyle = LABELS_ALONG_ORIGIN

        EditCommand_PM.__init__( self, command)

        # Hide Preview and Restore defaults buttons
        self.hideTopRowButtons(PM_RESTORE_DEFAULTS_BUTTON)


    def _addGroupBoxes(self):
        """
        Add the 1st group box to the Property Manager.
        """
        # Placement Options radio button list to create radio button list.
        # Format: buttonId, buttonText, tooltip
        PLACEMENT_OPTIONS_BUTTON_LIST = [ \
            ( 0, "Parallel to screen",     "Parallel to screen"     ),
            ( 1, "Through selected atoms", "Through selected atoms" ),
            ( 2, "Offset to a plane",      "Offset to a plane"      ),
            ( 3, "Custom",                 "Custom"                 )
        ]

        self.pmPlacementOptions = \
            PM_RadioButtonList( self,
                                title      = "Placement Options",
                                buttonList = PLACEMENT_OPTIONS_BUTTON_LIST,
                                checkedId  = 3 )

        self.pmGroupBox1 = PM_GroupBox(self, title = "Parameters")
        self._loadGroupBox1(self.pmGroupBox1)

        #image groupbox
        self.pmGroupBox2 = PM_GroupBox(self, title = "Image")
        self._loadGroupBox2(self.pmGroupBox2)

        #grid plane groupbox
        self.pmGroupBox3 = PM_GroupBox(self, title = "Grid")
        self._loadGroupBox3(self.pmGroupBox3)

    def _loadGroupBox3(self, pmGroupBox):
        """
        Load widgets in the grid plane group box.

        @param pmGroupBox: The grid  group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """
        self.gridPlaneCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Show grid",
                         widgetColumn  = 0,
                         setAsDefault = True,
                         spanWidth = True
                         )

        connect_checkbox_with_boolean_pref(
            self.gridPlaneCheckBox ,
            PlanePM_showGrid_prefs_key)


        self.gpXSpacingDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "X Spacing:",
                              value         =  4.000,
                              setAsDefault  =  True,
                              minimum       =  1.00,
                              maximum       =  200.0,
                              decimals      =  3,
                              singleStep    =  1.0,
                              spanWidth = False)

        self.gpYSpacingDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Y Spacing:",
                              value         =  4.000,
                              setAsDefault  =  True,
                              minimum       =  1.00,
                              maximum       =  200.0,
                              decimals      =  3,
                              singleStep    =  1.0,
                              spanWidth = False)

        lineTypeChoices = [ 'Dotted (default)',
                            'Dashed',
                            'Solid' ]

        self.gpLineTypeComboBox = \
            PM_ComboBox( pmGroupBox ,
                         label         =  "Line type:",
                         choices       =  lineTypeChoices,
                         setAsDefault  =  True)

        hhColorList = [ black, orange, red, magenta,
                        cyan, blue, white, yellow, gray ]
        hhColorNames = [ "Black (default)", "Orange", "Red", "Magenta",
                         "Cyan", "Blue", "White", "Yellow", "Other color..." ]

        self.gpColorTypeComboBox = \
            PM_ColorComboBox( pmGroupBox,
                              colorList = hhColorList,
                              colorNames = hhColorNames,
                              color = black )

        self.pmGroupBox5 = PM_GroupBox( pmGroupBox )

        self.gpDisplayLabels =\
            PM_CheckBox( self.pmGroupBox5,
                         text         = "Display labels",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True )

        originChoices = [ 'Lower left (default)',
                          'Upper left',
                          'Lower right',
                          'Upper right' ]

        self.gpOriginComboBox = \
            PM_ComboBox( self.pmGroupBox5 ,
                         label         =  "Origin:",
                         choices       =  originChoices,
                         setAsDefault  =  True )

        positionChoices = [ 'Origin axes (default)',
                            'Plane perimeter' ]

        self.gpPositionComboBox = \
            PM_ComboBox( self.pmGroupBox5 ,
                         label         =  "Position:",
                         choices       =  positionChoices,
                         setAsDefault  =  True)

        self._showHideGPWidgets()

        if env.prefs[PlanePM_showGridLabels_prefs_key]:
            self.displayLabels = True
            self.gpOriginComboBox.setEnabled( True )
            self.gpPositionComboBox.setEnabled( True )
        else:
            self.displayLabels = False
            self.gpOriginComboBox.setEnabled( False )
            self.gpPositionComboBox.setEnabled( False )

        return

    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """
        #TODO: Fix for bug: When you invoke a temporary mode
        # entering such a temporary mode keeps the signals of
        #PM from the previous mode connected (
        #but while exiting that temporary mode and reentering the
        #previous mode, it actually reconnects the signal! This gives rise to
        #lots  of bugs. This needs more general fix in Temporary mode API.
        # -- Ninad 2008-01-09 (similar comment exists in MovePropertyManager.py

        #UPDATE: (comment copied and modifief from BuildNanotube_PropertyManager.
        #The general problem still remains -- Ninad 2008-06-25

        if isConnect and self.isAlreadyConnected:
            if debug_flags.atom_debug:
                print_compact_stack("warning: attempt to connect widgets"\
                                    "in this PM that are already connected." )
            return

        if not isConnect and self.isAlreadyDisconnected:
            if debug_flags.atom_debug:
                print_compact_stack("warning: attempt to disconnect widgets"\
                                    "in this PM that are already disconnected.")
            return

        self.isAlreadyConnected = isConnect
        self.isAlreadyDisconnected = not isConnect

        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect

        change_connect(self.pmPlacementOptions.buttonGroup,
                       SIGNAL("buttonClicked(int)"),
                       self.changePlanePlacement)

        change_connect(self.widthDblSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.change_plane_width)

        change_connect(self.heightDblSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.change_plane_height)

        change_connect(self.aspectRatioCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self._enableAspectRatioSpinBox)


        #signal slot connection for imageDisplayCheckBox
        change_connect(self.imageDisplayCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.toggleFileChooserBehavior)

        #signal slot connection for imageDisplayFileChooser
        change_connect(self.imageDisplayFileChooser.lineEdit,
                       SIGNAL("editingFinished()"),
                       self.update_imageFile)

        #signal slot connection for heightfieldDisplayCheckBox
        change_connect(self.heightfieldDisplayCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.toggleHeightfield)

        #signal slot connection for heightfieldHQDisplayCheckBox
        change_connect(self.heightfieldHQDisplayCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.toggleHeightfieldHQ)

        #signal slot connection for heightfieldTextureCheckBox
        change_connect(self.heightfieldTextureCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.toggleTexture)

        #signal slot connection for vScaleSpinBox
        change_connect(self.vScaleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.change_vertical_scale)

        change_connect(self.plusNinetyButton,
                       SIGNAL("clicked()"),
                       self.rotate_90)

        change_connect(self.minusNinetyButton,
                       SIGNAL("clicked()"),
                       self.rotate_neg_90)

        change_connect(self.flipButton,
                       SIGNAL("clicked()"),
                       self.flip_image)

        change_connect(self.mirrorButton,
                       SIGNAL("clicked()"),
                       self.mirror_image)

        change_connect(self.gridPlaneCheckBox,
                       SIGNAL("stateChanged(int)"),
                       self.displayGridPlane)

        change_connect(self.gpXSpacingDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.changeXSpacingInGP)

        change_connect(self.gpYSpacingDoubleSpinBox,
                       SIGNAL("valueChanged(double)"),
                       self.changeYSpacingInGP)

        change_connect( self.gpLineTypeComboBox,
                        SIGNAL("currentIndexChanged(int)"),
                        self.changeLineTypeInGP )

        change_connect( self.gpColorTypeComboBox,
                        SIGNAL("editingFinished()"),
                        self.changeColorTypeInGP )

        change_connect( self.gpDisplayLabels,
                        SIGNAL("stateChanged(int)"),
                        self.displayLabelsInGP )

        change_connect( self.gpOriginComboBox,
                        SIGNAL("currentIndexChanged(int)"),
                        self.changeOriginInGP )

        change_connect( self.gpPositionComboBox,
                        SIGNAL("currentIndexChanged(int)"),
                        self.changePositionInGP )

        self._connect_checkboxes_to_global_prefs_keys()

        return

    def _connect_checkboxes_to_global_prefs_keys(self):
        """
        """
        connect_checkbox_with_boolean_pref(
            self.gridPlaneCheckBox ,
            PlanePM_showGrid_prefs_key)

        connect_checkbox_with_boolean_pref(
            self.gpDisplayLabels,
            PlanePM_showGridLabels_prefs_key)


    def changePositionInGP(self, idx):
        """
        Change Display of origin Labels (choices are along origin edges or along
        the plane perimeter.
        @param idx: Current index of the change grid label position combo box
        @type idx: int
        """
        if idx == 0:
            self.displayLabelStyle = LABELS_ALONG_ORIGIN
        elif idx == 1:
            self.displayLabelStyle = LABELS_ALONG_PLANE_EDGES
        else:
            print "Invalid index", idx
        return

    def changeOriginInGP(self, idx):
        """
        Change Display of origin Labels based on the location of the origin
        @param idx: Current index of the change origin position combo box
        @type idx: int
        """
        if idx == 0:
            self.originLocation = PLANE_ORIGIN_LOWER_LEFT
        elif idx ==1:
            self.originLocation = PLANE_ORIGIN_UPPER_LEFT
        elif idx == 2:
            self.originLocation = PLANE_ORIGIN_LOWER_RIGHT
        elif idx == 3:
            self.originLocation = PLANE_ORIGIN_UPPER_RIGHT
        else:
            print "Invalid index", idx
        return

    def displayLabelsInGP(self, state):
        """
        Choose to show or hide grid labels
        @param state: State of the Display Label Checkbox
        @type state: boolean
        """
        if env.prefs[PlanePM_showGridLabels_prefs_key]:
            self.gpOriginComboBox.setEnabled(True)
            self.gpPositionComboBox.setEnabled(True)
            self.displayLabels = True
            self.originLocation = PLANE_ORIGIN_LOWER_LEFT
            self.displayLabelStyle = LABELS_ALONG_ORIGIN
        else:
            self.gpOriginComboBox.setEnabled(False)
            self.gpPositionComboBox.setEnabled(False)
            self.displayLabels = False
        return

    def changeColorTypeInGP(self):
        """
        Change Color of grid
        """
        self.gridColor = self.gpColorTypeComboBox.getColor()
        return

    def changeLineTypeInGP(self, idx):
        """
        Change line type in grid
        @param idx: Current index of the Line type combo box
        @type idx: int
        """
        #line_type for actually drawing the grid is: 0=None, 1=Solid, 2=Dashed" or 3=Dotted
        if idx == 0:
            self.gridLineType = 3
        if idx == 1:
            self.gridLineType = 2
        if idx == 2:
            self.gridLineType = 1
        return

    def changeYSpacingInGP(self, val):
        """
        Change Y spacing on the grid
        @param val:value of Y spacing
        @type val: double
        """
        self.gridYSpacing = float(val)
        return

    def changeXSpacingInGP(self, val):
        """
        Change X spacing on the grid
        @param val:value of X spacing
        @type val: double
        """
        self.gridXSpacing = float(val)
        return

    def displayGridPlane(self, state):
        """
        Display or hide grid based on the state of the checkbox
        @param state: State of the Display Label Checkbox
        @type state: boolean
        """
        self._showHideGPWidgets()
        if self.gridPlaneCheckBox.isChecked():
            env.prefs[PlanePM_showGrid_prefs_key] = True
            self._makeGridPlane()
        else:
            env.prefs[PlanePM_showGrid_prefs_key] = False

        return

    def _makeGridPlane(self):
        """
        Show grid on the plane
        """
        #get all the grid related values in here
        self.gridXSpacing = float(self.gpXSpacingDoubleSpinBox.value())
        self.gridYSpacing = float(self.gpYSpacingDoubleSpinBox.value())

        #line_type for actually drawing the grid is: 0=None, 1=Solid, 2=Dashed" or 3=Dotted
        idx = self.gpLineTypeComboBox.currentIndex()
        self.changeLineTypeInGP(idx)
        self.gridColor = self.gpColorTypeComboBox.getColor()

        return


    def _showHideGPWidgets(self):
        """
        Enable Disable grid related widgets based on the state of the show grid
        checkbox.
        """
        if self.gridPlaneCheckBox.isChecked():
            self.gpXSpacingDoubleSpinBox.setEnabled(True)
            self.gpYSpacingDoubleSpinBox.setEnabled(True)
            self.gpLineTypeComboBox.setEnabled(True)
            self.gpColorTypeComboBox.setEnabled(True)
            self.gpDisplayLabels.setEnabled(True)
        else:
            self.gpXSpacingDoubleSpinBox.setEnabled(False)
            self.gpXSpacingDoubleSpinBox.setEnabled(False)
            self.gpYSpacingDoubleSpinBox.setEnabled(False)
            self.gpLineTypeComboBox.setEnabled(False)
            self.gpColorTypeComboBox.setEnabled(False)
            self.gpDisplayLabels.setEnabled(False)
        return

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in the image group box.

        @param pmGroupBox: The image group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """
        self.imageDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Display image",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.imageDisplayFileChooser = \
            PM_FileChooser(pmGroupBox,
                           label     = 'Image file:',
                           text      = '' ,
                           spanWidth = True,
                           filter    = "PNG (*.png);;"\
                           "All Files (*.*)"
                           )
        self.imageDisplayFileChooser.setEnabled(False)
        # add change image properties button

        BUTTON_LIST = [
            ( "QToolButton", 1,  "+90",
              "ui/actions/Properties Manager/RotateImage+90.png",
              "+90", "", 0),
            ( "QToolButton", 2,  "-90",
              "ui/actions/Properties Manager/RotateImage-90.png",
              "-90", "", 1),
            ( "QToolButton", 3,  "FLIP",
              "ui/actions/Properties Manager/FlipImageVertical.png",
              "Flip", "", 2),
            ( "QToolButton", 4,  "MIRROR",
              "ui/actions/Properties Manager/FlipImageHorizontal.png",
              "Mirror", "", 3)
        ]

        #image change button groupbox
        self.pmGroupBox2 = PM_GroupBox(pmGroupBox, title = "Modify Image")

        self.imageChangeButtonGroup = \
            PM_ToolButtonRow( self.pmGroupBox2,
                              title        = "",
                              buttonList   = BUTTON_LIST,
                              spanWidth    = True,
                              isAutoRaise  = False,
                              isCheckable  = False,
                              setAsDefault = True,
                              )

        self.imageChangeButtonGroup.buttonGroup.setExclusive(False)

        self.plusNinetyButton  = self.imageChangeButtonGroup.getButtonById(1)
        self.minusNinetyButton    = self.imageChangeButtonGroup.getButtonById(2)
        self.flipButton = self.imageChangeButtonGroup.getButtonById(3)
        self.mirrorButton   = self.imageChangeButtonGroup.getButtonById(4)

        # buttons enabled when a valid image is loaded
        self.mirrorButton.setEnabled(False)
        self.plusNinetyButton.setEnabled(False)
        self.minusNinetyButton.setEnabled(False)
        self.flipButton.setEnabled(False)

        self.heightfieldDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Create 3D relief",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.heightfieldHQDisplayCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "High quality",
                         widgetColumn  = 0,
                         state        = Qt.Unchecked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.heightfieldTextureCheckBox = \
            PM_CheckBox( pmGroupBox,
                         text         = "Use texture",
                         widgetColumn  = 0,
                         state        = Qt.Checked,
                         setAsDefault = True,
                         spanWidth = True
                         )

        self.vScaleSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        = " Vertical scale:",
                             value        = 1.0,
                             setAsDefault = True,
                             minimum      = -1000.0, # -1000 A
                             maximum      =  1000.0, # 1000 A
                             singleStep   = 0.1,
                             decimals     = 1,
                             suffix       = ' Angstroms')

        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)




    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in 1st group box.

        @param pmGroupBox: The 1st group box in the PM.
        @type  pmGroupBox: L{PM_GroupBox}
        """

        self.widthDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        = "Width:",
                             value        = 16.0,
                             setAsDefault = True,
                             minimum      = 1.0,
                             maximum      = 10000.0, # 1000 nm
                             singleStep   = 1.0,
                             decimals     = 1,
                             suffix       = ' Angstroms')



        self.heightDblSpinBox = \
            PM_DoubleSpinBox(pmGroupBox,
                             label        =" Height:",
                             value        = 16.0,
                             setAsDefault = True,
                             minimum      = 1.0,
                             maximum      = 10000.0, # 1000 nm
                             singleStep   = 1.0,
                             decimals     = 1,
                             suffix       = ' Angstroms')



        self.aspectRatioCheckBox = \
            PM_CheckBox(pmGroupBox,
                        text         = 'Maintain Aspect Ratio of:' ,
                        widgetColumn = 1,
                        state        = Qt.Unchecked
                        )


        self.aspectRatioSpinBox = \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "",
                              value         =  1.0,
                              setAsDefault  =  True,
                              minimum       =  0.1,
                              maximum       =  10.0,
                              singleStep    =  0.1,
                              decimals      =  2,
                              suffix        =  " to 1.00")

        if self.aspectRatioCheckBox.isChecked():
            self.aspectRatioSpinBox.setEnabled(True)
        else:
            self.aspectRatioSpinBox.setEnabled(False)

    def _addWhatsThisText(self):
        """
        What's This text for some of the widgets in this Property Manager.

        @note: Many PM widgets are still missing their "What's This" text.
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PlanePropertyManager
        whatsThis_PlanePropertyManager(self)


    def toggleFileChooserBehavior(self, checked):
        """
        Enables FileChooser and displays image when checkbox is checked otherwise
        not
        """
        self.imageDisplayFileChooser.lineEdit.emit(SIGNAL("editingFinished()"))
        if checked == Qt.Checked:
            self.imageDisplayFileChooser.setEnabled(True)
        elif checked == Qt.Unchecked:
            self.imageDisplayFileChooser.setEnabled(False)
            # if an image is already displayed, that's need to be hidden as well
        else:
            pass

        self.command.struct.glpane.gl_update()


    def toggleHeightfield(self, checked):
        """
        Enables 3D relief drawing mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.display_heightfield = checked
            if checked:
                self.heightfieldHQDisplayCheckBox.setEnabled(True)
                self.heightfieldTextureCheckBox.setEnabled(True)
                self.vScaleSpinBox.setEnabled(True)
                plane.computeHeightfield()
            else:
                self.heightfieldHQDisplayCheckBox.setEnabled(False)
                self.heightfieldTextureCheckBox.setEnabled(False)
                self.vScaleSpinBox.setEnabled(False)
                plane.heightfield = None
            plane.glpane.gl_update()

    def toggleHeightfieldHQ(self, checked):
        """
        Enables high quality rendering in 3D relief mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_hq = checked
            plane.computeHeightfield()
            plane.glpane.gl_update()

    def toggleTexture(self, checked):
        """
        Enables texturing in 3D relief mode.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_use_texture = checked
            # It is not necessary to re-compute the heightfield coordinates
            # at this point, they are re-computed whenever the "3D relief image"
            # checkbox is set.
            plane.glpane.gl_update()

    def update_spinboxes(self):
        """
        Update the width and height spinboxes.
        @see: Plane.resizeGeometry()
        This typically gets called when the plane is resized from the
        3D workspace (which marks assy as modified) .So, update the spinboxes
        that represent the Plane's width and height, but do no emit 'valueChanged'
        signal when the spinbox value changes.

        @see: Plane.resizeGeometry()
        @see: self._update_UI_do_updates()
        @see: Plane_EditCommand.command_update_internal_state()
        """
        # blockSignals = True make sure that spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().  This is done
        #because the spinbox valu changes as a result of resizing the plane
        #from the 3D workspace.
        if self.command.hasValidStructure():
            self.heightDblSpinBox.setValue(self.command.struct.height,
                                           blockSignals = True)
            self.widthDblSpinBox.setValue(self.command.struct.width,
                                          blockSignals = True)


    def update_imageFile(self):
        """
        Loads image file if path is valid
        """

        # Update buttons and checkboxes.
        self.mirrorButton.setEnabled(False)
        self.plusNinetyButton.setEnabled(False)
        self.minusNinetyButton.setEnabled(False)
        self.flipButton.setEnabled(False)
        self.heightfieldDisplayCheckBox.setEnabled(False)
        self.heightfieldHQDisplayCheckBox.setEnabled(False)
        self.heightfieldTextureCheckBox.setEnabled(False)
        self.vScaleSpinBox.setEnabled(False)

        plane = self.command.struct

        # Delete current image and heightfield
        plane.deleteImage()
        plane.heightfield = None
        plane.display_image = self.imageDisplayCheckBox.isChecked()

        if plane.display_image:
            imageFile = str(self.imageDisplayFileChooser.lineEdit.text())

            from model.Plane import checkIfValidImagePath
            validPath = checkIfValidImagePath(imageFile)

            if validPath:
                from PIL import Image

                # Load image from file
                plane.image = Image.open(imageFile)
                plane.loadImage(imageFile)

                # Compute the relief image
                plane.computeHeightfield()

                if plane.image:
                    self.mirrorButton.setEnabled(True)
                    self.plusNinetyButton.setEnabled(True)
                    self.minusNinetyButton.setEnabled(True)
                    self.flipButton.setEnabled(True)
                    self.heightfieldDisplayCheckBox.setEnabled(True)
                    if plane.display_heightfield:
                        self.heightfieldHQDisplayCheckBox.setEnabled(True)
                        self.heightfieldTextureCheckBox.setEnabled(True)
                        self.vScaleSpinBox.setEnabled(True)


    def show(self):
        """
        Show the Plane Property Manager.
        """
        EditCommand_PM.show(self)
        #It turns out that if updateCosmeticProps is called before
        #EditCommand_PM.show, the 'preview' properties are not updated
        #when you are editing an existing plane. Don't know the cause at this
        #time, issue is trivial. So calling it in the end -- Ninad 2007-10-03

        if self.command.struct:

            plane = self.command.struct
            plane.updateCosmeticProps(previewing = True)
            if plane.imagePath:
                self.imageDisplayFileChooser.setText(plane.imagePath)
            self.imageDisplayCheckBox.setChecked(plane.display_image)

            #Make sure that the plane placement option is always set to
            #'Custom' when the Plane PM is shown. This makes sure that bugs like
            #2949 won't occur. Let the user change the plane placement option
            #explicitely
            button = self.pmPlacementOptions.getButtonById(3)
            button.setChecked(True)

    def setParameters(self, params):
        """
        """
        width, height, gridColor, gridLineType, \
             gridXSpacing, gridYSpacing, originLocation, \
             displayLabelStyle = params

        # blockSignals = True  flag makes sure that the
        # spinbox.valueChanged()
        # signal is not emitted after calling spinbox.setValue().
        self.widthDblSpinBox.setValue(width, blockSignals = True)
        self.heightDblSpinBox.setValue(height, blockSignals = True)
        self.win.glpane.gl_update()


        self.gpColorTypeComboBox.setColor(gridColor)
        self.gridLineType = gridLineType

        self.gpXSpacingDoubleSpinBox.setValue(gridXSpacing)
        self.gpYSpacingDoubleSpinBox.setValue(gridYSpacing)

        self.gpOriginComboBox.setCurrentIndex(originLocation)
        self.gpPositionComboBox.setCurrentIndex(displayLabelStyle)


    def getCurrrentDisplayParams(self):
        """
        Returns a tuple containing current display parameters such as current
        image path and grid display params.
        @see: Plane_EditCommand.command_update_internal_state() which uses this
        to decide whether to modify the structure (e.g. because of change in the
        image path or display parameters.)
        """
        imagePath = self.imageDisplayFileChooser.text
        gridColor = self.gpColorTypeComboBox.getColor()

        return (imagePath, gridColor, self.gridLineType,
                self.gridXSpacing, self.gridYSpacing,
                self.originLocation, self.displayLabelStyle)

    def getParameters(self):
        """
        """
        width = self.widthDblSpinBox.value()
        height = self.heightDblSpinBox.value()
        gridColor = self.gpColorTypeComboBox.getColor()

        params = (width, height, gridColor, self.gridLineType,
                  self.gridXSpacing, self.gridYSpacing, self.originLocation,
                  self.displayLabelStyle)

        return params


    def change_plane_width(self, newWidth):
        """
        Slot for width spinbox in the Property Manager.

        @param newWidth: width in Angstroms.
        @type  newWidth: float
        """
        if self.aspectRatioCheckBox.isChecked():
            self.command.struct.width   =  newWidth
            self.command.struct.height  =  self.command.struct.width / \
                self.aspectRatioSpinBox.value()
            self.update_spinboxes()
        else:
            self.change_plane_size()
        self._updateAspectRatio()

    def change_plane_height(self, newHeight):
        """
        Slot for height spinbox in the Property Manager.

        @param newHeight: height in Angstroms.
        @type  newHeight: float
        """
        if self.aspectRatioCheckBox.isChecked():
            self.command.struct.height  =  newHeight
            self.command.struct.width   =  self.command.struct.height * \
                self.aspectRatioSpinBox.value()
            self.update_spinboxes()
        else:
            self.change_plane_size()
        self._updateAspectRatio()

    def change_plane_size(self, gl_update = True):
        """
        Slot to change the Plane's width and height.

        @param gl_update: Forces an update of the glpane.
        @type  gl_update: bool
        """
        self.command.struct.width   =  self.widthDblSpinBox.value()
        self.command.struct.height  =  self.heightDblSpinBox.value()
        if gl_update:
            self.command.struct.glpane.gl_update()

    def change_vertical_scale(self, scale):
        """
        Changes vertical scaling of the heightfield.
        """
        if self.command and self.command.struct:
            plane = self.command.struct
            plane.heightfield_scale = scale
            plane.computeHeightfield()
            plane.glpane.gl_update()

    def changePlanePlacement(self, buttonId):
        """
        Slot to change the placement of the plane depending upon the
        option checked in the "Placement Options" group box of the PM.

        @param buttonId: The button id of the selected radio button (option).
        @type  buttonId: int
        """

        if buttonId == 0:
            msg = "Create a Plane parallel to the screen. "\
                "With <b>Parallel to Screen</b> plane placement option, the "\
                "center of the plane is always (0,0,0)"
            self.updateMessage(msg)
            self.command.placePlaneParallelToScreen()
        elif buttonId == 1:
            msg = "Create a Plane with center coinciding with the common center "\
                "of <b> 3 or more selected atoms </b>. If exactly 3 atoms are "\
                "selected, the Plane will pass through those atoms."
            self.updateMessage(msg)
            self.command.placePlaneThroughAtoms()
            if self.command.logMessage:
                env.history.message(self.command.logMessage)
        elif buttonId == 2:
            msg = "Create a Plane at an <b>offset</b> to the selected plane "\
                "indicated by the direction arrow. "\
                "you can click on the direction arrow to reverse its direction."
            self.updateMessage(msg)
            self.command.placePlaneOffsetToAnother()
            if self.command.logMessage:
                env.history.message(self.command.logMessage)
        elif buttonId == 3:
            #'Custom' plane placement. Do nothing (only update message box)
            # Fixes bug 2439
            msg = "Create a plane with a <b>Custom</b> plane placement. "\
                "The plane is placed parallel to the screen, with "\
                "center at (0, 0, 0). User can then modify the plane placement."
            self.updateMessage(msg)


    def _enableAspectRatioSpinBox(self, enable):
        """
        Slot for "Maintain Aspect Ratio" checkbox which enables or disables
        the Aspect Ratio spin box.

        @param enable: True = enable, False = disable.
        @type  enable: bool
        """

        self.aspectRatioSpinBox.setEnabled(enable)

    def _updateAspectRatio(self):
        """
        Updates the Aspect Ratio spin box based on the current width and height.
        """
        aspectRatio = self.command.struct.width / self.command.struct.height
        self.aspectRatioSpinBox.setValue(aspectRatio)

    def _update_UI_do_updates(self):
        """
        Overrides superclass method.
        @see: Command_PropertyManager._update_UI_do_updates() for documentation.

        @see: Plane.resizeGeometry()
        @see: self.update_spinboxes()
        @see: Plane_EditCommand.command_update_internal_state()
        """
        #This typically gets called when the plane is resized from the
        #3D workspace (which marks assy as modified) . So, update the spinboxes
        #that represent the Plane's width and height.
        self.update_spinboxes()


    def update_props_if_needed_before_closing(self):
        """
        This updates some cosmetic properties of the Plane (e.g. fill color,
        border color, etc.) before closing the Property Manager.
        """

        # Example: The Plane Property Manager is open and the user is
        # 'previewing' the plane. Now the user clicks on "Build > Atoms"
        # to invoke the next command (without clicking "Done").
        # This calls openPropertyManager() which replaces the current PM
        # with the Build Atoms PM.  Thus, it creates and inserts the Plane
        # that was being previewed. Before the plane is permanently inserted
        # into the part, it needs to change some of its cosmetic properties
        # (e.g. fill color, border color, etc.) which distinguishes it as
        # a new plane in the part. This function changes those properties.
        # ninad 2007-06-13

        #called in updatePropertyManager in MWsemeantics.py --(Partwindow class)

        EditCommand_PM.update_props_if_needed_before_closing(self)

        #Don't draw the direction arrow when the object is finalized.
        if self.command.struct and \
           self.command.struct.offsetParentGeometry:

            dirArrow = self.command.struct.offsetParentGeometry.directionArrow
            dirArrow.setDrawRequested(False)

    def updateMessage(self, msg = ''):
        """
        Updates the message box with an informative message
        @param message: Message to be displayed in the Message groupbox of
                        the property manager
        @type  message: string
        """
        self.MessageGroupBox.insertHtmlMessage(msg,
                                               setAsDefault = False,
                                               minLines     = 5)

    def rotate_90(self):
        """
        Rotate the image clockwise.
        """
        if self.command.hasValidStructure():
            self.command.struct.rotateImage(0)
        return

    def rotate_neg_90(self):
        """
        Rotate the image counterclockwise.
        """
        if self.command.hasValidStructure():
            self.command.struct.rotateImage(1)
        return

    def flip_image(self):
        """
        Flip the image horizontally.
        """
        if self.command.hasValidStructure():
            self.command.struct.mirrorImage(1)
        return

    def mirror_image(self):
        """
        Flip the image vertically.
        """
        if self.command.hasValidStructure():
            self.command.struct.mirrorImage(0)
        return
class GrapheneGeneratorPropertyManager(EditCommand_PM):
    """
    The GrapheneGeneratorPropertyManager class provides a Property Manager
    for the "Build > Graphene (Sheet)" command.
    """
    # The title that appears in the property manager header.
    title = "Graphene Generator"
    # The name of this property manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to PNG file that appears in the header.
    iconPath = "ui/actions/Tools/Build Structures/Graphene.png"

    def __init__(self, command):
        """
        Construct the "Build Graphene" Property Manager.
        """
        _superclass.__init__(self, command)

        msg = "Edit the parameters below and click the <b>Preview</b> "\
            "button to preview the graphene sheet. Clicking <b>Done</b> "\
            "inserts it into the model."

        self.updateMessage(msg=msg)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_CANCEL_BUTTON | \
                                PM_PREVIEW_BUTTON | \
                                PM_WHATS_THIS_BUTTON)

    def _addGroupBoxes(self):
        """
        Add the group boxes to the Graphene Property Manager dialog.
        """
        self.pmGroupBox1 = \
            PM_GroupBox( self,
                         title = "Graphene Parameters" )

        self._loadGroupBox1(self.pmGroupBox1)

    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in groubox 1.
        """

        self.heightField = \
            PM_DoubleSpinBox( pmGroupBox,
                              label        = "Height :",
                              value        = 20.0,
                              setAsDefault = True,
                              minimum      = 1.0,
                              maximum      = 100.0,
                              singleStep   = 1.0,
                              decimals     = 3,
                              suffix       = ' Angstroms')
        self.widthField = \
            PM_DoubleSpinBox( pmGroupBox,
                              label        = "Width :",
                              value        = 20.0,
                              setAsDefault = True,
                              minimum      = 1.0,
                              maximum      = 100.0,
                              singleStep   = 1.0,
                              decimals     = 3,
                              suffix       = ' Angstroms')

        self.bondLengthField = \
            PM_DoubleSpinBox( pmGroupBox,
                              label        = "Bond Length :",
                              value        = CC_GRAPHITIC_BONDLENGTH,
                              setAsDefault = True,
                              minimum      = 1.0,
                              maximum      = 3.0,
                              singleStep   = 0.1,
                              decimals     = 3,
                              suffix       = ' Angstroms')

        endingChoices = ["None", "Hydrogen", "Nitrogen"]

        self.endingsComboBox= \
            PM_ComboBox( pmGroupBox,
                         label        = "Endings :",
                         choices      = endingChoices,
                         index        = 0,
                         setAsDefault = True,
                         spanWidth    = False )

    def getParameters(self):
        """
        Return the parameters from this property manager
        to be used to create the graphene sheet.
        @return: A tuple containing the parameters
        @rtype: tuple
        @see: L{Graphene_EditCommand._gatherParameters()} where this is used
        """

        height = self.heightField.value()
        width = self.widthField.value()
        bond_length = self.bondLengthField.value()
        endings = self.endingsComboBox.currentIndex()

        return (height, width, bond_length, endings)

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.  
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_GrapheneGeneratorPropertyManager
        whatsThis_GrapheneGeneratorPropertyManager(self)

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_GrapheneGeneratorPropertyManager
        ToolTip_GrapheneGeneratorPropertyManager(self)
Пример #9
0
class PeptideGeneratorPropertyManager(PM_Dialog):
    """
    The PeptideGeneratorPropertyManager class provides a Property Manager 
    for the "Build > Peptide" command.
    """
    # The title that appears in the property manager header.
    title = "Peptide Generator"
    # The name of this property manager. This will be set to
    # the name of the PropMgr (this) object via setObjectName().
    pmName = title
    # The relative path to PNG file that appears in the header.
    iconPath = "ui/actions/Tools/Build Structures/Peptide.png"

    def __init__(self):
        """Construct the Peptide Property Manager.
        """
        PM_Dialog.__init__(self, self.pmName, self.iconPath, self.title)

        # phi psi angles will define the secondary structure of the peptide chain
        self.phi = -57.0
        self.psi = -47.0
        self.chirality = 1
        self.ss_idx = 1
        self.peptide_cache = []

        self.updateMessageGroupBox()

    def updateMessageGroupBox(self):
        msg = ""

        msg = msg + "Click on the Amino Acid buttons to add a new residuum to\
            the polypeptide chain. Click <b>Done</b> to insert it into the project."

        # This causes the "Message" box to be displayed as well.
        # setAsDefault=True causes this message to be reset whenever
        # this PropMgr is (re)displayed via show(). Mark 2007-06-01.
        self.MessageGroupBox.insertHtmlMessage(msg, setAsDefault=True)

    def _addGroupBoxes(self):
        """
        Add the group boxe to the Peptide Property Manager dialog.
        """
        self.pmGroupBox1 = \
            PM_GroupBox( self,
                         title          = "Peptide Parameters" )

        # Add group box widgets.
        self._loadGroupBox1(self.pmGroupBox1)

    def _loadGroupBox1(self, inPmGroupBox):
        """
        Load widgets in the group box.
        """

        memberChoices = [
            "Custom", "Alpha helix", "Beta strand", "Pi helix", "3_10 helix",
            "Polyproline-II helix", "Fully extended"
        ]

        self.aaTypeComboBox= \
            PM_ComboBox( inPmGroupBox,
                         label        = "Conformation :",
                         choices      = memberChoices,
                         index        = 1,
                         setAsDefault = True,
                         spanWidth    = False )

        self.connect(self.aaTypeComboBox, SIGNAL("currentIndexChanged(int)"),
                     self._aaTypeChanged)

        self.phiAngleField = \
            PM_DoubleSpinBox( inPmGroupBox,
                              label        = "Phi angle :",
                              value        = -57.0,
                              setAsDefault = True,
                              minimum      = -180.0,
                              maximum      = 180.0,
                              singleStep   = 1.0,
                              decimals     = 1,
                              suffix       = " degrees")

        self.connect(self.phiAngleField, SIGNAL("valueChanged(double)"),
                     self._aaPhiAngleChanged)

        self.phiAngleField.setEnabled(False)

        self.psiAngleField = \
            PM_DoubleSpinBox( inPmGroupBox,
                              label        = "Psi angle :",
                              value        = -47.0,
                              setAsDefault = True,
                              minimum      = -180.0,
                              maximum      = 180.0,
                              singleStep   = 1.0,
                              decimals     = 1,
                              suffix       = " degrees" )

        self.connect(self.psiAngleField, SIGNAL("valueChanged(double)"),
                     self._aaPsiAngleChanged)

        self.psiAngleField.setEnabled(False)


        self.invertChiralityPushButton = \
            PM_PushButton( inPmGroupBox,
                           text         = 'Invert chirality' ,
                           spanWidth    = False
                       )

        self.connect(self.invertChiralityPushButton, SIGNAL("clicked()"),
                     self._aaChiralityChanged)

        self.aaTypesButtonGroup = \
            PM_ToolButtonGrid( inPmGroupBox,
                               buttonList = AA_BUTTON_LIST,
                               label      = "Amino acids :",
                               checkedId  = 0,
                               setAsDefault = True )

        self.connect(self.aaTypesButtonGroup.buttonGroup,
                     SIGNAL("buttonClicked(int)"), self._setAminoAcidType)

        self.sequenceEditor = \
            PM_TextEdit( inPmGroupBox,
                         label      = "Sequence",
                         spanWidth = True )

        self.sequenceEditor.insertHtml("", False, 4, 10, True)

        self.sequenceEditor.setReadOnly(True)

        self.startOverButton = \
            PM_PushButton( inPmGroupBox,
                           label     = "",
                           text      = "Start Over",
                           spanWidth = True,
                           setAsDefault = True )

        self.connect(self.startOverButton, SIGNAL("clicked()"),
                     self._startOverClicked)

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.  
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_PeptideGeneratorPropertyManager
        whatsThis_PeptideGeneratorPropertyManager(self)

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_PeptideGeneratorPropertyManager
        ToolTip_PeptideGeneratorPropertyManager(self)

    def _aaChiralityChanged(self):
        """
        Set chirality of the peptide chain.
        """
        self.psi *= -1
        self.phi *= -1

        self.phiAngleField.setValue(self.phi)
        self.psiAngleField.setValue(self.psi)

    def _aaTypeChanged(self, idx):
        """
        Slot for Peptide Structure Type combobox.
        Changes phi/psi angles for secondary structure.
        """
        self.ss_idx = idx

        if idx == 0:
            self.phiAngleField.setEnabled(True)
            self.psiAngleField.setEnabled(True)
        else:
            self.phiAngleField.setEnabled(False)
            self.psiAngleField.setEnabled(False)

        if idx == 1:  # alpha helix
            self.phi = -57.0
            self.psi = -47.0
        elif idx == 2:  # beta strand
            self.phi = -135.0
            self.psi = 135.0
        elif idx == 3:  # 3-10 helix
            self.phi = -55.0
            self.psi = -70.0
        elif idx == 4:  # pi helix
            self.phi = -49.0
            self.psi = -26.0
        elif idx == 5:  # polyprolin-II
            self.phi = -75.0
            self.psi = 150.0
        elif idx == 6:  # fully extended
            self.phi = -180.0
            self.psi = 180.0
        else:
            self.phi = self.phiAngleField.value()
            self.psi = self.psiAngleField.value()

        self.phi *= self.chirality
        self.psi *= self.chirality

        self.phiAngleField.setValue(self.phi)
        self.psiAngleField.setValue(self.psi)
        pass

    def _aaPhiAngleChanged(self, phi):
        self.phi = self.phiAngleField.value()
        pass

    def _aaPsiAngleChanged(self, psi):
        self.psi = self.psiAngleField.value()
        pass

    def _setAminoAcidType(self, aaTypeIndex):
        """
        Adds a new amino acid to the peptide molecule.
        """
        button, idx, short_name, dum, name, symbol, x, y = AA_BUTTON_LIST[
            aaTypeIndex]
        if self.ss_idx == 1:
            aa_txt = "<font color=red>"
        elif self.ss_idx == 2:
            aa_txt = "<font color=blue>"
        elif self.ss_idx == 3:
            aa_txt = "<font color=green>"
        elif self.ss_idx == 4:
            aa_txt = "<font color=orange>"
        elif self.ss_idx == 5:
            aa_txt = "<font color=magenta>"
        elif self.ss_idx == 6:
            aa_txt = "<font color=darkblue>"
        else:
            aa_txt = "<font color=black>"

        aa_txt += symbol + "</font>"
        self.sequenceEditor.insertHtml(aa_txt, False, 4, 10, False)
        self.addAminoAcid(aaTypeIndex)
        pass

    def _startOverClicked(self):
        """
        Resets a sequence in the sequence editor window.
        """
        self.sequenceEditor.clear()
        self.peptide_cache = []
        pass
Пример #10
0
class InsertPeptide_PropertyManager(EditCommand_PM):
    """
    The InsertPeptide_PropertyManager class provides a Property Manager 
    for the "Insert > Peptide" command.
    """
    # The title that appears in the property manager header.
    title = "Insert Peptide"
    # The name of this property manager. This will be set to
    # the name of the PropMgr (this) object via setObjectName().
    pmName = title
    # The relative path to PNG file that appears in the header.
    iconPath = "ui/actions/Command Toolbar/BuildProtein/InsertPeptide.png"

    # phi psi angles will define the secondary structure of the peptide chain
    phi = -57.0
    psi = -47.0
    chirality = 1
    secondary = SS_HELIX
    current_amino_acid = 7 # Glycine
    
    # DEPRECATED ATTRS
    #peptide_cache = []
    #peptide_cache.append((0, 0, 0))
        
    def __init__( self, command ):
        """
        Construct the Property Manager.
        """
        _superclass.__init__( self, command )
               
               
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_CANCEL_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
        return
        
    def show(self):
        """
        Extends superclass method.
        """
        _superclass.show(self)
        self.updateMessage("Choose the peptide parameters below, then click "\
                           "two endpoints in the graphics area to insert a "\
                           "peptide chain.")
        return
    
    def getParameters(self):
        """
        Return the parameters from this property manager
        to be used to create the  peptide.
        @return: A tuple containing the parameters
        @rtype: tuple
        @see: L{InsertPeptide_EditCommand._gatherParameters()} where this is used        
        """
        return (self.secondary, self.phi, self.psi, self.current_amino_acid)

    def _addGroupBoxes(self):
        """
        Add the group boxe to the Peptide Property Manager dialog.
        """
        self.pmGroupBox1 = \
            PM_GroupBox( self, 
                         title          = "Peptide Parameters" )

        # Add group box widgets.
        self._loadGroupBox1(self.pmGroupBox1)
        return

    def _loadGroupBox1(self, inPmGroupBox):
        """
        Load widgets in the group box.
        """

        memberChoices = ["Custom", 
                         "Alpha helix", 
                         "Beta strand",
                         "Pi helix", 
                         "3_10 helix", 
                         "Polyproline-II helix",
                         "Fully extended"]

        self.aaTypeComboBox= \
            PM_ComboBox( inPmGroupBox,
                         label        = "Conformation:", 
                         choices      = memberChoices, 
                         index        = 1, 
                         setAsDefault = True,
                         spanWidth    = False )

        self.connect( self.aaTypeComboBox,
                      SIGNAL("currentIndexChanged(int)"),
                      self._aaTypeChanged)

        self.phiAngleField = \
            PM_DoubleSpinBox( inPmGroupBox,
                              label        = "Phi angle:", 
                              value        = self.phi, 
                              setAsDefault = True,
                              minimum      = -180.0, 
                              maximum      = 180.0, 
                              singleStep   = 1.0, 
                              decimals     = 1, 
                              suffix       = " degrees")

        self.connect( self.phiAngleField,
                      SIGNAL("valueChanged(double)"),
                      self._aaPhiAngleChanged)

        self.phiAngleField.setEnabled(False)

        self.psiAngleField = \
            PM_DoubleSpinBox( inPmGroupBox,
                              label        = "Psi angle:", 
                              value        = self.psi, 
                              setAsDefault = True,
                              minimum      = -180.0, 
                              maximum      = 180.0, 
                              singleStep   = 1.0, 
                              decimals     = 1, 
                              suffix       = " degrees" )

        self.connect( self.psiAngleField,
                      SIGNAL("valueChanged(double)"),
                      self._aaPsiAngleChanged)

        self.psiAngleField.setEnabled(False)        

        self.aaTypesButtonGroup = \
            PM_ToolButtonGrid( inPmGroupBox, 
                               buttonList   = AA_BUTTON_LIST,
                               label        = "Amino acids",
                               checkedId    = self.current_amino_acid, # Glycine
                               setAsDefault = True )

        self.connect( self.aaTypesButtonGroup.buttonGroup,
                      SIGNAL("buttonClicked(int)"),
                      self._setAminoAcidType)
        return
    
    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.  
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_InsertPeptide_PropertyManager
        whatsThis_InsertPeptide_PropertyManager(self)
        return

    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_InsertPeptide_PropertyManager
        ToolTip_InsertPeptide_PropertyManager(self)
        return

    def _aaChiralityChanged(self):
        """
        Set chirality of the peptide chain. 
        """

        # This feature is currently disable as it was confusing to the users
        # who expected control over chirality of amino acids (D/L conformers)
        # rather than over polypeptide chain (left/right-handed structure).

        self.psi *= -1
        self.phi *= -1

        self.phiAngleField.setValue(self.phi)
        self.psiAngleField.setValue(self.psi)
        return

    def _aaTypeChanged(self, idx):
        """
        Slot for Peptide Structure Type combo box. Changes phi/psi angles 
        for secondary structure.
        
        @param idx: index of secondary structure combo box
        @type idx: int
        """
        self.ss_idx = idx

        if idx == 0:
            self.phiAngleField.setEnabled(True)
            self.psiAngleField.setEnabled(True)
        else:
            self.phiAngleField.setEnabled(False)
            self.psiAngleField.setEnabled(False)

        if idx == 1: # alpha helix
            self.phi = -57.0
            self.psi = -47.0
            self.secondary = SS_HELIX
        elif idx == 2: # beta strand
            self.phi = -135.0
            self.psi = 135.0
            self.secondary = SS_STRAND
        elif idx == 3: # 3-10 helix
            self.phi = -55.0
            self.psi = -70.0
            self.secondary = SS_HELIX
        elif idx == 4: # pi helix
            self.phi = -49.0
            self.psi = -26.0
            self.secondary = SS_HELIX
        elif idx == 5: # polyprolin-II
            self.phi = -75.0
            self.psi = 150.0
            self.secondary = SS_COIL
        elif idx == 6: # fully extended
            self.phi = -180.0
            self.psi = 180.0
            self.secondary = SS_STRAND
        else:
            self.phi = self.phiAngleField.value()
            self.psi = self.psiAngleField.value()
            self.secondary = SS_COIL
            
        self.phi *= self.chirality
        self.psi *= self.chirality

        self.command.secondary = self.secondary
        
        self.phiAngleField.setValue(self.phi)
        self.psiAngleField.setValue(self.psi)
        return

    def _aaPhiAngleChanged(self, phi):
        """
        Called when phi angle spin box has changed. 
        
        @param phi: phi angle value
        @type phi: float
        """
        self.phi = self.phiAngleField.value()
        return


    def _aaPsiAngleChanged(self, psi):
        """
        Called when psi angle spin box has changed. 
        
        @param psi: psi angle value
        @type psi: float
        """
        self.psi = self.psiAngleField.value()
        return

    def _setAminoAcidType(self, index):
        """
        Sets the current amino acid type to I{index}.
        """
        self.current_amino_acid = index
        return
    
    # --------------------------------------------------------------------
    # Deprecated methods to keep until we're certain this is working.
    # --Mark 2008-12-12.
    
    def addAminoAcid_DEPRECATED(self, index):
        """
        Adds a new amino acid to the peptide molecule.        
        """

        # This commened out code is obsolete in interactive peptide builder.
        # The interactive peptide builder creates homopeptides.
        
        # add a new amino acid and chain conformation to the peptide cache
        #self.peptide_cache.append((index,self.phi,self.psi))
        #self.peptide_cache[0] = (index,self.phi,self.psi)
        
        self.current_amino_acid = index
        return
    
    def _setAminoAcidType_DEPRECATED(self, aaTypeIndex):
        """
        Adds a new amino acid to the peptide molecule.
        """
        # piotr 080911: this method is obsolete as of 080911. It was used in 
        # the old Peptide Generator.
        button, idx, short_name, dum, name, symbol, x, y = AA_BUTTON_LIST[aaTypeIndex]
        if self.ss_idx==1:
            aa_txt = "<font color=red>"
        elif self.ss_idx==2:
            aa_txt = "<font color=blue>"
        elif self.ss_idx==3:
            aa_txt = "<font color=green>"
        elif self.ss_idx==4:
            aa_txt = "<font color=orange>"
        elif self.ss_idx==5:
            aa_txt = "<font color=magenta>"
        elif self.ss_idx==6:
            aa_txt = "<font color=darkblue>"
        else:
            aa_txt = "<font color=black>"

        aa_txt += symbol+"</font>"
        #self.sequenceEditor.insertHtml(aa_txt, False, 4, 10, False)
        return
class DnaDuplexPropertyManager( DnaOrCnt_PropertyManager ):
    """
    The DnaDuplexPropertyManager class provides a Property Manager
    for the B{Build > DNA > Duplex} command.

    @ivar title: The title that appears in the property manager header.
    @type title: str

    @ivar pmName: The name of this property manager. This is used to set
                  the name of the PM_Dialog object via setObjectName().
    @type name: str

    @ivar iconPath: The relative path to the PNG file that contains a
                    22 x 22 icon image that appears in the PM header.
    @type iconPath: str
    """

    title         =  "Insert DNA"
    pmName        =  title
    iconPath      =  "ui/actions/Tools/Build Structures/InsertDsDna.png"

    def __init__( self, win, editCommand ):
        """
        Constructor for the DNA Duplex property manager.
        """
        self.endPoint1 = None
        self.endPoint2 = None

        self._conformation  = "B-DNA"
        self._numberOfBases = 0
        self._basesPerTurn  = getDuplexBasesPerTurn(self._conformation)
        self._duplexRise    = getDuplexRise(self._conformation)
        self._duplexLength  = getDuplexLength(self._conformation,
                                              self._numberOfBases)


        _superclass.__init__( self,
                              win,
                              editCommand)

        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_CANCEL_BUTTON | \
                                PM_WHATS_THIS_BUTTON)


    def connect_or_disconnect_signals(self, isConnect):
        """
        Connect or disconnect widget signals sent to their slot methods.
        This can be overridden in subclasses. By default it does nothing.
        @param isConnect: If True the widget will send the signals to the slot
                          method.
        @type  isConnect: boolean
        """
        if isConnect:
            change_connect = self.win.connect
        else:
            change_connect = self.win.disconnect


        change_connect(self._placementOptions.buttonGroup,
                       SIGNAL("buttonClicked(int)"),
                       self.activateSpecifyReferencePlaneTool)

        change_connect( self.conformationComboBox,
                        SIGNAL("currentIndexChanged(int)"),
                        self.conformationComboBoxChanged )

        change_connect( self.numberOfBasePairsSpinBox,
                        SIGNAL("valueChanged(int)"),
                        self.numberOfBasesChanged )

        change_connect( self.basesPerTurnDoubleSpinBox,
                        SIGNAL("valueChanged(double)"),
                        self.basesPerTurnChanged )

        change_connect( self.duplexRiseDoubleSpinBox,
                        SIGNAL("valueChanged(double)"),
                        self.duplexRiseChanged )

        change_connect(self.showCursorTextCheckBox,
                       SIGNAL('stateChanged(int)'),
                       self._update_state_of_cursorTextGroupBox)
        
        self.duplexRiseDoubleSpinBox.connectWithState(
            Preferences_StateRef_double( bdnaRise_prefs_key, 
                                         env.prefs[bdnaRise_prefs_key] )
            )
        
        self.basesPerTurnDoubleSpinBox.connectWithState(
            Preferences_StateRef_double( bdnaBasesPerTurn_prefs_key, 
                                         env.prefs[bdnaBasesPerTurn_prefs_key] )
            )

        
                
 
    def ok_btn_clicked(self):
        """
        Slot for the OK button
        """
        if self.editCommand:
            self.editCommand.preview_or_finalize_structure(previewing = False)
            ##env.history.message(self.editCommand.logMessage)
        self.win.toolsDone()

    def cancel_btn_clicked(self):
        """
        Slot for the Cancel button.
        """
        if self.editCommand:
            self.editCommand.cancelStructure()
        self.win.toolsCancel()


    def _update_widgets_in_PM_before_show(self):
        """
        Update various widgets  in this Property manager.
        Overrides superclass method

        @see: MotorPropertyManager._update_widgets_in_PM_before_show
        @see: self.show where it is called.
        """
        pass

    def getFlyoutActionList(self):
        """ returns custom actionlist that will be used in a specific mode
        or editing a feature etc Example: while in movie mode,
        the _createFlyoutToolBar method calls
        this """


        #'allActionsList' returns all actions in the flyout toolbar
        #including the subcontrolArea actions
        allActionsList = []

        #Action List for  subcontrol Area buttons.
        #In this mode there is really no subcontrol area.
        #We will treat subcontrol area same as 'command area'
        #(subcontrol area buttons will have an empty list as their command area
        #list). We will set  the Comamnd Area palette background color to the
        #subcontrol area.

        subControlAreaActionList =[]

        self.exitEditCommandAction.setChecked(True)
        subControlAreaActionList.append(self.exitEditCommandAction)

        separator = QAction(self.w)
        separator.setSeparator(True)
        subControlAreaActionList.append(separator)


        allActionsList.extend(subControlAreaActionList)

        #Empty actionlist for the 'Command Area'
        commandActionLists = []

        #Append empty 'lists' in 'commandActionLists equal to the
        #number of actions in subControlArea
        for i in range(len(subControlAreaActionList)):
            lst = []
            commandActionLists.append(lst)

        params = (subControlAreaActionList, commandActionLists, allActionsList)

        return params

    def _addGroupBoxes( self ):
        """
        Add the DNA Property Manager group boxes.
        """
        self._pmReferencePlaneGroupBox = PM_GroupBox( self,
                                                      title = "Placement Options" )
        self._loadReferencePlaneGroupBox( self._pmReferencePlaneGroupBox )

        self._pmGroupBox1 = PM_GroupBox( self, title = "Endpoints" )
        self._loadGroupBox1( self._pmGroupBox1 )

        self._pmGroupBox1.hide()

        self._pmGroupBox2 = PM_GroupBox( self, title = "Parameters" )
        self._loadGroupBox2( self._pmGroupBox2 )

        self._displayOptionsGroupBox = PM_GroupBox( self,
                                                    title = "Display Options" )
        self._loadDisplayOptionsGroupBox( self._displayOptionsGroupBox )


    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in group box 3.
        """
        #Folllowing toolbutton facilitates entering a temporary DnaLineMode
        #to create a DNA using endpoints of the specified line.
        self.specifyDnaLineButton = PM_ToolButton(
            pmGroupBox,
            text = "Specify Endpoints",
            iconPath  = "ui/actions/Properties Manager/Pencil.png",
            spanWidth = True
        )
        self.specifyDnaLineButton.setCheckable(True)
        self.specifyDnaLineButton.setAutoRaise(True)
        self.specifyDnaLineButton.setToolButtonStyle(
            Qt.ToolButtonTextBesideIcon)

        #EndPoint1 and endPoint2 coordinates. These widgets are hidden
        # as of 2007- 12 - 05
        self._endPoint1SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox,
                                                          label = "End Point 1")
        self.x1SpinBox = self._endPoint1SpinBoxes.xSpinBox
        self.y1SpinBox = self._endPoint1SpinBoxes.ySpinBox
        self.z1SpinBox = self._endPoint1SpinBoxes.zSpinBox

        self._endPoint2SpinBoxes = PM_CoordinateSpinBoxes(pmGroupBox,
                                                          label = "End Point 2")
        self.x2SpinBox = self._endPoint2SpinBoxes.xSpinBox
        self.y2SpinBox = self._endPoint2SpinBoxes.ySpinBox
        self.z2SpinBox = self._endPoint2SpinBoxes.zSpinBox

        self._endPoint1SpinBoxes.hide()
        self._endPoint2SpinBoxes.hide()

    def _loadGroupBox2(self, pmGroupBox):
        """
        Load widgets in group box 4.
        """

        self.conformationComboBox  = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Conformation:",
                         choices       =  ["B-DNA"],
                         setAsDefault  =  True)

        dnaModelChoices = ['PAM3', 'PAM5']
        self.dnaModelComboBox = \
            PM_ComboBox( pmGroupBox,
                         label         =  "Model:",
                         choices       =  dnaModelChoices,
                         setAsDefault  =  True)


        self.basesPerTurnDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Bases per turn:",
                              value         =  env.prefs[bdnaBasesPerTurn_prefs_key],
                              setAsDefault  =  True,
                              minimum       =  8.0,
                              maximum       =  20.0,
                              decimals      =  2,
                              singleStep    =  0.1 )
        
        
        self.duplexRiseDoubleSpinBox  =  \
            PM_DoubleSpinBox( pmGroupBox,
                              label         =  "Rise:",
                              value         =  env.prefs[bdnaRise_prefs_key],
                              setAsDefault  =  True,
                              minimum       =  2.0,
                              maximum       =  4.0,
                              decimals      =  3,
                              singleStep    =  0.01 )
        
        
        

        # Strand Length (i.e. the number of bases)
        self.numberOfBasePairsSpinBox = \
            PM_SpinBox( pmGroupBox,
                        label         =  "Base pairs:",
                        value         =  self._numberOfBases,
                        setAsDefault  =  False,
                        minimum       =  0,
                        maximum       =  10000 )

        self.numberOfBasePairsSpinBox.setDisabled(True)

        # Duplex Length
        self.duplexLengthLineEdit  =  \
            PM_LineEdit( pmGroupBox,
                         label         =  "Duplex length: ",
                         text          =  "0.0 Angstroms",
                         setAsDefault  =  False)

        self.duplexLengthLineEdit.setDisabled(True)


    def _loadDisplayOptionsGroupBox(self, pmGroupBox):
        """
        Load widgets in the Display Options GroupBox
        @see: DnaOrCnt_PropertyManager. _loadDisplayOptionsGroupBox
        """
        #Call the superclass method that loads the cursor text checkboxes.
        #Note, as of 2008-05-19, the superclass, DnaOrCnt_PropertyManager
        #only loads the cursor text groupboxes. Subclasses like this can
        #call custom methods like self._loadCursorTextCheckBoxes etc if they
        #don't need all groupboxes that the superclass loads.
        _superclass._loadDisplayOptionsGroupBox(self, pmGroupBox)

        self._rubberbandLineGroupBox = PM_GroupBox(
            pmGroupBox,
            title = 'Rubber band line:')

        dnaLineChoices = ['Ribbons', 'Ladder']
        self.dnaRubberBandLineDisplayComboBox = \
            PM_ComboBox( self._rubberbandLineGroupBox ,
                         label         =  " Display as:",
                         choices       =  dnaLineChoices,
                         setAsDefault  =  True)

        self.lineSnapCheckBox = \
            PM_CheckBox(self._rubberbandLineGroupBox ,
                        text         = 'Enable line snap' ,
                        widgetColumn = 1,
                        state        = Qt.Checked
                    )

    def _connect_showCursorTextCheckBox(self):
        """
        Connect the show cursor text checkbox with user prefs_key.
        Overrides
        DnaOrCnt_PropertyManager._connect_showCursorTextCheckBox
        """
        connect_checkbox_with_boolean_pref(
            self.showCursorTextCheckBox ,
            dnaDuplexEditCommand_showCursorTextCheckBox_prefs_key)


    def _params_for_creating_cursorTextCheckBoxes(self):
        """
        Returns params needed to create various cursor text checkboxes connected
        to prefs_keys  that allow custom cursor texts.
        @return: A list containing tuples in the following format:
                ('checkBoxTextString' , preference_key). PM_PrefsCheckBoxes
                uses this data to create checkboxes with the the given names and
                connects them to the provided preference keys. (Note that
                PM_PrefsCheckBoxes puts thes within a GroupBox)
        @rtype: list
        @see: PM_PrefsCheckBoxes
        @see: self._loadDisplayOptionsGroupBox where this list is used.
        @see: Superclass method which is overridden here --
        DnaOrCnt_PropertyManager._params_for_creating_cursorTextCheckBoxes()
        """
        params = \
        [  #Format: (" checkbox text", prefs_key)
            ("Number of base pairs",
             dnaDuplexEditCommand_cursorTextCheckBox_numberOfBasePairs_prefs_key),

            ("Number of turns",
             dnaDuplexEditCommand_cursorTextCheckBox_numberOfTurns_prefs_key),

            ("Duplex length",
             dnaDuplexEditCommand_cursorTextCheckBox_length_prefs_key),

            ("Angle",
             dnaDuplexEditCommand_cursorTextCheckBox_angle_prefs_key) ]

        return params


    def _addToolTipText(self):
        """
        Tool Tip text for widgets in the DNA Property Manager.
        """
        pass


    def conformationComboBoxChanged( self, inIndex ):
        """
        Slot for the Conformation combobox. It is called whenever the
        Conformation choice is changed.

        @param inIndex: The new index.
        @type  inIndex: int
        """
        conformation  =  self.conformationComboBox.currentText()

        if conformation == "B-DNA":
            self.basesPerTurnDoubleSpinBox.setValue("10.0")

        elif conformation == "Z-DNA":
            self.basesPerTurnDoubleSpinBox.setValue("12.0")

        else:
            msg = redmsg("conformationComboBoxChanged(): \
                         Error - unknown DNA conformation. Index = "+ inIndex)
            env.history.message(msg)

        self.duplexLengthSpinBox.setSingleStep(getDuplexRise(conformation))

    def numberOfBasesChanged( self, numberOfBases ):
        """
        Slot for the B{Number of Bases} spinbox.
        """
        # Update the Duplex Length lineEdit widget.
        text = str(getDuplexLength(self._conformation,
                                   numberOfBases,
                                   self._duplexRise)) \
             + " Angstroms"
        self.duplexLengthLineEdit.setText(text)
        return

    def basesPerTurnChanged( self, basesPerTurn ):
        """
        Slot for the B{Bases per turn} spinbox.
        """
        self.editCommand.basesPerTurn = basesPerTurn
        self._basesPerTurn = basesPerTurn
        return

    def duplexRiseChanged( self, rise ):
        """
        Slot for the B{Rise} spinbox.
        """
        self.editCommand.duplexRise = rise
        self._duplexRise = rise
        return

    def getParameters(self):
        """
        Return the parameters from this property manager
        to be used to create the DNA duplex.
        @return: A tuple containing the parameters
        @rtype: tuple
        @see: L{DnaDuplex_EditCommand._gatherParameters} where this is used
        """
        numberOfBases = self.numberOfBasePairsSpinBox.value()
        dnaForm  = str(self.conformationComboBox.currentText())
        basesPerTurn = self.basesPerTurnDoubleSpinBox.value()
        duplexRise = self.duplexRiseDoubleSpinBox.value()

        dnaModel = str(self.dnaModelComboBox.currentText())

        # First endpoint (origin) of DNA duplex
        x1 = self.x1SpinBox.value()
        y1 = self.y1SpinBox.value()
        z1 = self.z1SpinBox.value()

        # Second endpoint (direction vector/axis) of DNA duplex.
        x2 = self.x2SpinBox.value()
        y2 = self.y2SpinBox.value()
        z2 = self.z2SpinBox.value()

        if not self.endPoint1:
            self.endPoint1 = V(x1, y1, z1)
        if not self.endPoint2:
            self.endPoint2 = V(x2, y2, z2)

        return (numberOfBases,
                dnaForm,
                dnaModel,
                basesPerTurn,
                duplexRise,
                self.endPoint1,
                self.endPoint2)

    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.
        """
        whatsThis_DnaDuplexPropertyManager(self)
class GrapheneGeneratorPropertyManager(EditCommand_PM):
    """
    The GrapheneGeneratorPropertyManager class provides a Property Manager
    for the "Build > Graphene (Sheet)" command.
    """
    # The title that appears in the property manager header.
    title = "Graphene Generator"
    # The name of this property manager. This will be set to
    # the name of the PM_Dialog object via setObjectName().
    pmName = title
    # The relative path to PNG file that appears in the header.
    iconPath = "ui/actions/Tools/Build Structures/Graphene.png"
    
    def __init__( self, command ):
        """
        Construct the "Build Graphene" Property Manager.
        """
        _superclass.__init__( self, command )
               
        msg = "Edit the parameters below and click the <b>Preview</b> "\
            "button to preview the graphene sheet. Clicking <b>Done</b> "\
            "inserts it into the model."
        
        self.updateMessage(msg = msg)
        
        self.showTopRowButtons( PM_DONE_BUTTON | \
                                PM_CANCEL_BUTTON | \
                                PM_PREVIEW_BUTTON | \
                                PM_WHATS_THIS_BUTTON)
                
    def _addGroupBoxes(self):
        """
        Add the group boxes to the Graphene Property Manager dialog.
        """
        self.pmGroupBox1 = \
            PM_GroupBox( self, 
                         title = "Graphene Parameters" )
        
        self._loadGroupBox1(self.pmGroupBox1)
              
    def _loadGroupBox1(self, pmGroupBox):
        """
        Load widgets in groubox 1.
        """
        
        self.heightField = \
            PM_DoubleSpinBox( pmGroupBox,
                              label        = "Height :", 
                              value        = 20.0, 
                              setAsDefault = True,
                              minimum      = 1.0, 
                              maximum      = 100.0, 
                              singleStep   = 1.0, 
                              decimals     = 3, 
                              suffix       = ' Angstroms')
        self.widthField = \
            PM_DoubleSpinBox( pmGroupBox,
                              label        = "Width :", 
                              value        = 20.0, 
                              setAsDefault = True,
                              minimum      = 1.0, 
                              maximum      = 100.0, 
                              singleStep   = 1.0, 
                              decimals     = 3, 
                              suffix       = ' Angstroms')
        
        self.bondLengthField = \
            PM_DoubleSpinBox( pmGroupBox,
                              label        = "Bond Length :", 
                              value        = CC_GRAPHITIC_BONDLENGTH, 
                              setAsDefault = True,
                              minimum      = 1.0, 
                              maximum      = 3.0, 
                              singleStep   = 0.1, 
                              decimals     = 3, 
                              suffix       = ' Angstroms')
        
        endingChoices = ["None", "Hydrogen", "Nitrogen"]
        
        self.endingsComboBox= \
            PM_ComboBox( pmGroupBox,
                         label        = "Endings :", 
                         choices      = endingChoices, 
                         index        = 0, 
                         setAsDefault = True,
                         spanWidth    = False )
        
        
    def getParameters(self):
        """
        Return the parameters from this property manager
        to be used to create the graphene sheet.
        @return: A tuple containing the parameters
        @rtype: tuple
        @see: L{Graphene_EditCommand._gatherParameters()} where this is used
        """
        
        height = self.heightField.value()
        width = self.widthField.value()
        bond_length = self.bondLengthField.value()
        endings = self.endingsComboBox.currentIndex()
        
        return (height, width, bond_length, endings)
            
    def _addWhatsThisText(self):
        """
        What's This text for widgets in this Property Manager.  
        """
        from ne1_ui.WhatsThisText_for_PropertyManagers import whatsThis_GrapheneGeneratorPropertyManager
        whatsThis_GrapheneGeneratorPropertyManager(self)
        
    def _addToolTipText(self):
        """
        Tool Tip text for widgets in this Property Manager.  
        """
        from ne1_ui.ToolTipText_for_PropertyManagers import ToolTip_GrapheneGeneratorPropertyManager
        ToolTip_GrapheneGeneratorPropertyManager(self)