#=======================================================================================
#
#    CTaskShelxeMR.py : CTaskShelxeMR(CCP4TaskWidget)
#    
#    Author  : Kyle Stevenson,STFC
#    Created : 16th Sep. 2015, KJS
#
#    Gui Class for refinement of MR solutions using Shelxe
#
#=======================================================================================


from PyQt4 import QtGui,QtCore
import CCP4TaskWidget
import CCP4Widgets

class CTaskAcorn(CCP4TaskWidget.CTaskWidget):
    
    TASKNAME    = 'acorn'
    TASKVERSION = 1.0
    TASKMODULE  ='expt_phasing'
    
    TASKTITLE       = "ACORN - Phase Refinement with Dynamic Density Modification"
    SHORTTASKTITLE  = "ACORN"
    
    DESCRIPTION     = "Un-biased improvement of initial phases for high resolution data (1.5 Angstoms and better)"
    ERROR_CODES = {  200 : { 'description' : 'Space group of reflection and phases file does not match' } } 
    WHATNEXT = ['coot_rebuild','prosmart_refmac','buccaneer_build_refine_mr'] 
    MGDISPLAYFILES  = ['FPHIOUT']


    def __init__(self, parent):
        CCP4TaskWidget.CTaskWidget.__init__(self,parent)

    def drawContents(self):
        self.setProgramHelpFile('acorn')  # Comes in two varieties; version 1 needs the reflections & the model; version 2 also needs the phase info.
        
        folder1 = self.openFolder(folderFunction='inputData',title='Input Data')
        self.createLine( [ 'label', 'Run ACORN with ', 'widget', '-guiMode', 'radio', 'ACORN_PHSIN_TYPE' ] )
        self.openSubFrame( frame=[True] )
        self.createLine(['subtitle', 'Reflection Data','Integrated reflection data for experimental phasing.'])
        self.createLine( [ 'widget', 'F_SIGF' ] )
        self.createLine( [ 'widget', 'ABCD' ], toggle=[ 'ACORN_PHSIN_TYPE', 'open', 'phases'] )
        self.closeSubFrame()
    
        self.openSubFrame( frame=[True], toggle=[ 'ACORN_PHSIN_TYPE', 'open', 'model'] )
        self.createLine(['subtitle', 'Model for approximate co-ordinates','Model for approximate co-ordinates (if known)'])
        self.createLine( ['widget', 'XYZIN'] )
        self.closeSubFrame()
        
        self.createLine( [ 'tip', 'Extend the resolution of the data for use in ACORN', 'label', 'Artificially extend resolution','widget', 'ACORN_EXTEND', 'label',' to','widget', 'ACORN_EXTENDRES', 'label','Angstoms'] )
        #self.openSubFrame( frame=[False], toggle=[ 'ACORN_EXTEND', 'open', [True] ] )
        #self.createLine( [ 'tip', 'Resolution to extend to', 'label','Extend resolution to ','widget', 'ACORN_EXTENDRES', 'label','Angstoms' ]  )
        #self.closeSubFrame()
        self.createLine( [ 'tip', 'Apply resolution anisotropy correction to data', 'label', 'Anisotropy Correction','widget', 'ACORN_ANISOTROPY' ] )
        
        folder2 = self.openFolder(folderFunction='acornGenParam',title='Advanced Acorn Parameters')
        self.createLine(['subtitle', 'General Run Parameters','General Parameter Choice'])
        self.createLine( [ 'tip', 'Custom ', 'widget', 'ACORN_BGRID', 'label', 'Choose a user defined grid size' ] )
        self.openSubFrame( frame=[True], toggle=[ 'ACORN_BGRID', 'open', [True] ] )
        self.createLine( [ 'tip', 'GRID keyword', 'label','Grid Size (Angstroms)','widget', 'ACOGEN_GRID' ] )
        self.closeSubFrame()
        self.createLine( [ 'tip', 'Info', 'widget', 'ACORN_BSEED', 'label', 'Choose a user defined random number seed for ACORN' ] )
        self.openSubFrame( frame=[True], toggle=[ 'ACORN_BSEED', 'open', [True] ] )
        self.createLine( [ 'tip', 'SEED keyword', 'label','Random Number Seed','widget', 'ACOGEN_SEED' ] )
        self.closeSubFrame()
    
        #folder3 = self.openFolder(folderFunction='acornReflectParam',title='Selection of Reflection Data')
        self.createLine(['subtitle', 'Selection of Reflection Data','Reflection Data Settings'])
        self.createLine( [ 'tip', 'Use reflections within resolution range if ticked, all data used otherwise', 'widget', 'ACORN_BRESOL', 'label', 'User defined resolution range for reflection data' ] )
        self.openSubFrame( frame=[True], toggle=[ 'ACORN_BRESOL', 'open', [True] ] )
        self.createLine( [ 'tip', 'RESOLUTION keyword, Low Resolution Limit', 'label','Use reflections within resolution limit of ', 'widget', 'ACOREF_RESOLL', 'label', 'Angstrom' ] )
        self.createLine( [ 'tip', 'RESOLUTION keyword, High Resolution Limit', 'label','to a limit of', 'widget', 'ACOREF_RESOLU', 'label', 'Angstrom' ] )
        self.closeSubFrame()
        
        self.createLine( [ 'tip', 'The reflections with FP less than cut*SIGFP will be rejected and treated as extended reflections', 'widget', 'ACORN_BEXCLUDE', 'label', 'Exclude low SIGFP reflections' ] )
        self.openSubFrame( frame=[True], toggle=[ 'ACORN_BEXCLUDE', 'open', [True] ] )
        self.createLine( [ 'tip', 'EXCLUDE keyword', 'label','Reject reflections that are less than ','widget', 'ACOREF_EXCLUDE' ,'label', '* the standard deviation (sigma)' ] )
        self.closeSubFrame()
        self.createLine( [ 'tip', 'The reflections with E-values greater than a certain cut will be rejected', 'widget', 'ACORN_BECUT', 'label', 'Exclude reflections that are high E-value outliers' ] )
        self.openSubFrame( frame=[True], toggle=[ 'ACORN_BECUT', 'open', [True] ] )
        self.createLine( [ 'tip', 'ECUT keyword', 'label','Reject observed reflections with E-values greater than ','widget', 'ACOREF_ECUT' ] )
        self.closeSubFrame()
        
        #folder4 = self.openFolder(folderFunction='acornPhasePar',title='Acorn Phase Parameters')
        self.createLine(['subtitle', 'Acorn Phase Settings','Phase Settings'])
        self.createLine( [ 'tip', 'SUPP keyword', 'widget', 'ACOPH_PATSUP', 'label','Use the Paterson Superposition Function' ] )
        self.createLine( [ 'tip', 'NTRY keyword', 'label','Number of Trials','widget', 'ACOPH_NUMTRIALS' ] )
        self.createLine( [ 'tip', 'MAXSET keyword', 'label', 'Number of initials phase sets to refine','widget', 'ACOPH_MAXSET' ] )
        self.createLine( [ 'tip', 'CUTDDM keyword', 'label', 'Upper density limit for Dynamic Density Modification (DDM)','widget', 'ACOPH_CUTDDM' ] )
        self.createLine( [ 'tip', 'PSFINISH keyword', 'label', 'Cease DDM cycling if phase shift between consecutive cycles is less than','widget', 'ACOPH_PSFINISH' ] )
        self.createLine( [ 'tip', 'CCFINISH keyword', 'label', 'Cease phase refinement if correlation coefficient exceeds','widget', 'ACOPH_CCFINISH' ] )

        self.openSubFrame( frame=[True], toggle=[ 'ACORN_PHSIN_TYPE', 'open', 'model'] )

        self.createLine(['subtitle', 'Model Input Settings','Model Settings'])
        self.createLine( [ 'label', 'Run ACORN with ', 'widget', '-guiMode', 'radio', 'ACORN_MODEL_USE' ] )
        # Several options available . Use ACORN_MODEL_SELECT, 3 options.
        # Use All Atoms (already the default)
        # Use Single Fragment of a certain length starting at a particular atom. NAFRAG from NSTART
        # Use Number of fragments, of fixed length. POSI number of fragments, at length NAFRAG.
        self.createLine( [ 'tip', 'The start position of the fragment in the model file', 'label','Start fragment at atom number ','widget', 'ACORN_NSTART' ], toggle=[ 'ACORN_MODEL_USE', 'open', 'one'])
        self.createLine( [ 'tip', 'Fragment is this long in terms of atoms', 'label','Length of fragment ','widget', 'ACORN_NAFRAG' ], toggle=[ 'ACORN_MODEL_USE', 'open', 'one'])
        
        self.createLine( [ 'tip', 'Number of fragments in set', 'label','Number of fragments to pick ','widget', 'ACORN_POSI' ], toggle=[ 'ACORN_MODEL_USE', 'open', 'set'])
        self.createLine( [ 'tip', 'Length of each fragment', 'label','Length of each fragment ','widget', 'ACORN_NAFRAG' ], toggle=[ 'ACORN_MODEL_USE', 'open', 'set'])
        self.closeSubFrame()

    def taskValidity(self):
        import CCP4ErrorHandling
        rv = CCP4ErrorHandling.CErrorReport()
        # Check the space group is same in both input Mini-MTZ files 
        if self.container.inputData.F_SIGF.exists():
            fsig_sg = str(self.container.inputData.F_SIGF.fileContent.spaceGroup)
        else:
            fsig_sg = None
        if self.container.inputData.ABCD.exists():
            phifom_sg = str(self.container.inputData.ABCD.fileContent.spaceGroup)
        else:
            phifom_sg = None
        if fsig_sg is not None and phifom_sg is not None and fsig_sg != phifom_sg:
            rv.append(self.__class__,200,details='Reflections file space group:'+ fsig_sg +' Phases file space group:'+ phifom_sg ,stack=False)

        return rv        