
import CCP4RvapiParser
class arp_warp_classic_report(CCP4RvapiParser.RvapiReport):
  TASKNAME="arp_warp_classic"

"""
from CCP4ReportParser import *

class arp_warp_classic_report(Report):
  # Specify which gui task and/or pluginscript this applies to
  TASKNAME = 'arp_warp_classic'
  # Flag that a 'Running' mode is supported
  RUNNING = True
  # Indicate css version that this code was written against
  CSS_VERSION = '0.1.0'
  def __init__(self,xmlnode=None,jobInfo={},jobStatus=None,taskVersion=None,**kw):
    Report. __init__(self,xmlnode=xmlnode,jobInfo=jobInfo,cssVersion=self.CSS_VERSION,**kw)
    if self.errorReport().maxSeverity()>SEVERITY_WARNING:
      print 'FAILED instantiating buccaneer_build_refine_mr report generator'
      self.errorReport().report()
      return

    # 'nooutput' mode would be used by another report class that wanted
    # to use some method(s) from this class for its own report
    if jobStatus is not None and jobStatus.lower() == 'nooutput':
      return
    elif jobStatus.count('Running'):
      #summaryFold = self.addFold(label='Summary by cycle', initiallyOpen=True)
      self.runningText(self)
      self.summaryTable(self)
      self.completenessGraph(self)
      clearingDiv = self.addDiv(style="clear:both;")

    else:
      results = self.addResults()
      #summaryFold = results.addFold(label='Summary by cycle', initiallyOpen=True)
      self.finishedText()
      self.table1(self)
      self.completenessGraph(self)
      clearingDiv = self.addDiv(style="clear:both;")
      self.details(self)
      self.picture(self)
  
  def summaryTable(self, parent=None):
    if parent is None:
        parent=self
    if self.xmlnode.haspath("//BuccaneerBuildRefineResult"):
        xmlPath = '//BuccaneerBuildRefineResult/BuildRefineCycle'
        xmlNodes = self.xmlnode.xpath(xmlPath)
        if len(xmlNodes)>0:
            selectString = "//BuccaneerBuildRefineResult/BuildRefineCycle[1] "
            if len(xmlNodes)>2:
                selectString += " | //BuccaneerBuildRefineResult/BuildRefineCycle[%d]" % (len(xmlNodes)-1)
            if len(xmlNodes)>1:
                selectString += " | //BuccaneerBuildRefineResult/BuildRefineCycle[%d]" % len(xmlNodes)
            tableDiv = parent.addDiv(style="height:250px;width:30em;float:left;border:0px solid black;")
            progressTable = tableDiv.addTable(select=selectString)
            progressTable.addData(title="Cycle", select="Number")
            progressTable.addData(title="Completeness by residue", select="BuccaneerResult/Final/CompletenessByResiduesBuilt")
            progressTable.addData(title="Completeness by chains", select="BuccaneerResult/Final/CompletenessByChainsBuilt")
            progressTable.addData(title="R<sub>Work</sub>", select="RefmacResult/r_factor")
            progressTable.addData(title="R<sub>Free</sub>",   select="RefmacResult/r_free",   expr="x if float(x)>=0.0 else '-'")

  def completenessGraph(self,parent=None):
    graph = parent.addFlotGraph( title="Progress by build-refine iteration", select="//BuccaneerBuildRefineResult/BuildRefineCycle",style="height:300px; width:450px; float:right; border:0px;")
    graph.addData (title="Cycle",  select="Number" )
    graph.addData (title="Compl<sub>res</sub>", select="BuccaneerResult/Final/CompletenessByResiduesBuilt")
#    graph.addData (title="by_chains", select="BuccaneerResult/Final/CompletenessByChainsBuilt")
    graph.addData (title="R<sub>Work</sub>", select="RefmacResult/r_factor")
    graph.addData (title="R<sub>Free</sub>",  select="RefmacResult/r_free" )

    graph.addData (title="RMS<sub>Bonds</sub>", select="RefmacResult/rmsBONDx100", expr="x/100.0" )
    graph.addData (title="RMS<sub>Angles</sub>",  select="RefmacResult/rmsANGLE" ) 


    p = graph.addPlotObject()
    p.append('title','Progress by iteration')
    textLabel = p.append("text",xpos=3,ypos=0.5)
    textLabel.text = "foobar";
    p.append('plottype','xy')
    p.append('xintegral','true')
    p.append('xlabel','Cycle')
    p.append('ylabel','Completeness')
    l = p.append('plotline',xcol=1,ycol=2)
    l.append('label','By residue')
    l.append('colour','blue')
#    l = p.append('plotline',xcol=1,ycol=3)
#    l.append('label','By chain')
#    l.append('colour','red')

    #p.append('yrange', rightaxis='true', min='auto',max='auto')
    p.append('yrange', rightaxis='false', min='0.0',max='1.0')

    l = p.append('plotline',xcol=1,ycol=4,rightaxis='true')
    l.append('colour','gold')
    l = p.append('plotline',xcol=1,ycol=3,rightaxis='true')
    l.append('colour','lightblue')

    if len(p.validate())>0: print p.validate()
    
    p = graph.addPlotObject()
    p.append('title','R-factors after each iteration')
    p.append('plottype','xy')
    p.append('xintegral','true')
    p.append('xlabel','Cycle')
    l = p.append('plotline',xcol=1,ycol=4)
    l.append('label','R<sub>Free</sub>')
    l.append('colour','gold')
    l = p.append('plotline',xcol=1,ycol=3)
    l.append('label','R<sub>Work</sub>')
    l.append('colour','lightblue')
    if len(p.validate())>0: print p.validate()

    p = graph.addPlotObject()
    p.append('title','Geometry after each iteration')
    #p.append('yrange', rightaxis='true', min='auto',max='auto')
    p.append('plottype','xy')
    p.append('xintegral','true')
    p.append('xlabel','Cycle')
    l = p.append('plotline',xcol=1,ycol=5, rightaxis='true')
    l.append('label','RMS<sub>Bonds</sub>')
    l.append('colour','firebrick')
    l = p.append('plotline',xcol=1,ycol=6)
    l.append('label','RMS<sub>Angles</sub>')
    l.append('colour','green')
    if len(p.validate())>0: print p.validate()
    
  def details(self,parent=None):
    if parent is None:
        parent = self
    fold = parent.addFold(label="Detailed progress by iteration")
    table = fold.addTable(select="//BuccaneerBuildRefineResult/BuildRefineCycle", transpose=True, downloadable=True,id='details')
    
    table.addData ( title='Iteration', select='Number', expr='int(x)' )

    for title,select in [ [ "Completeness by residue" ,"BuccaneerResult/Final/CompletenessByResiduesBuilt" ],
                          [ "Completeness by chains" , "BuccaneerResult/Final/CompletenessByChainsBuilt"  ]]:
        table.addData(title=title,select=select,expr='round(x,2)')
    for title,select in  [[ "Number of chains"  , "BuccaneerResult/Final/ChainsBuilt"],
                          [ "Residues built" , "BuccaneerResult/Final/ResiduesBuilt" ],
                          [ "Residues sequenced" , "BuccaneerResult/Final/ResiduesSequenced"],
                          [ "Longest fragment" , "BuccaneerResult/Final/ResiduesLongestFragment" ],
                          [ "Number of fragments" , "BuccaneerResult/Final/FragmentsBuilt" ] ]:
        table.addData(title=title,select=select)
    for title,select,expr in  [[ "R<sub>Work</sub>"  , "RefmacResult/r_factor", "x"],
                          [ "R<sub>Free</sub>" , "RefmacResult/r_free","x if float(x)>0.0 else '-' " ],
                          [ "RMS<sub>Bonds</sub>" , "RefmacResult/rmsBONDx100", "round(x/100,3)"],
                          [ "RMS<sub>Angles</sub>", "RefmacResult/rmsANGLE","x" ] ]:
        table.addData(title=title,select=select,expr=expr)
            
  def table1(self,parent=None):
    if parent is None:
        parent = self
    tableDiv = parent.addDiv(style="height:30em;width:20em;float:left;border:0px;")
    table = tableDiv.addTable(select="//BuccaneerBuildRefineResult", transpose=True, id='table_1') 
    for title,select in  [[ "Completeness by residue" ,"BuildRefineCycle[last()]/BuccaneerResult/Final/CompletenessByResiduesBuilt" ],
                          [ "Completeness by chains" , "BuildRefineCycle[last()]/BuccaneerResult/Final/CompletenessByChainsBuilt"  ]]:
        table.addData(title=title,select=select,expr='round(x,2)')
    for title,select in  [[ "Number of chains"  , "BuildRefineCycle[last()]/BuccaneerResult/Final/ChainsBuilt"],
                          [ "Residues built" , "BuildRefineCycle[last()]/BuccaneerResult/Final/ResiduesBuilt" ],
                          [ "Residues sequenced" , "BuildRefineCycle[last()]/BuccaneerResult/Final/ResiduesSequenced"],
                          [ "Longest fragment" , "BuildRefineCycle[last()]/BuccaneerResult/Final/ResiduesLongestFragment" ],
                          [ "Number of fragments" , "BuildRefineCycle[last()]/BuccaneerResult/Final/FragmentsBuilt" ] ]:
        table.addData(title=title,select=select)
    for title,select,expr in  [[ "R<sub>Work</sub>"  , "BuildRefineCycle[last()]/RefmacResult/r_factor", "x"],
                          [ "R<sub>Free</sub>" , "BuildRefineCycle[last()]/RefmacResult/r_free","x if float(x)>0.0 else '-' " ],
                          [ "RMS<sub>Bonds</sub>" , "BuildRefineCycle[last()]/RefmacResult/rmsBONDx100", "round(x/100,3)"],
                          [ "RMS<sub>Angles</sub>", "BuildRefineCycle[last()]/RefmacResult/rmsANGLE","x" ] ]:
        table.addData(title=title,select=select,expr=expr)

  def picture(self,parent=None) :
#   sceneFile = '$CCP4I2/pipelines/bucref_mr/script/buccaneer_1.scene.xml'
    sceneFile = '$CCP4I2/wrappers/arp_warp_classic/script/arp_warp_classic_1.scene.xml'
    pic = parent.addPicture(label="Autobuilt structure",sceneFile=sceneFile,id='autobuild_1')

  def runningText(self,parent=None) :
    if parent is None: parent = self
    parent.append ( "<p><b>The job is currently running. Updates will be shown here for each iteration of model building and refinement.</b></p>" )
    self.finishedText()
       
  def finishedText(self,parent=None) :
    if parent is None: parent = self
    try:
      cres = float(self.xmlnode.xpath('BuildRefineCycle/BuccaneerResult/Final/CompletenessByResiduesBuilt')[-1].text)
      cchn = float(self.xmlnode.xpath('BuildRefineCycle/BuccaneerResult/Final/CompletenessByChainsBuilt')[-1].text)
      frgb = float(self.xmlnode.xpath('BuildRefineCycle/BuccaneerResult/Final/FragmentsBuilt')[-1].text)
      chnb = float(self.xmlnode.xpath('BuildRefineCycle/BuccaneerResult/Final/ChainsBuilt')[-1].text)
      resb = float(self.xmlnode.xpath('BuildRefineCycle/BuccaneerResult/Final/ResiduesBuilt')[-1].text)
      ress = float(self.xmlnode.xpath('BuildRefineCycle/BuccaneerResult/Final/ResiduesSequenced')[-1].text)
      parent.append( "<p>%d residues were built in %d fragments. Of these, %d residues were assigned to the sequence.</p><p>The number of chains is estimated to be %d. Of these chains, %5.1f%% of the residues have been built.<br/>Of the residues that were built, %5.1f%% were assigned to a chain.</p>"%(resb,frgb,ress,chnb,100*cchn,100*cres) )
    except Exception,e:
      parent.append( "<p>Model building results are not yet available.</p>" )
      print >> sys.stderr, "ERROR buccaneer_build_refine_mr_report ",e
    try:
      rwrk = float(self.xmlnode.xpath('BuildRefineCycle/RefmacResult/r_factor')[-1].text)
      rfre = float(self.xmlnode.xpath('BuildRefineCycle/RefmacResult/r_free')[-1].text)
      rbnd = float(self.xmlnode.xpath('BuildRefineCycle/RefmacResult/rmsBONDx100')[-1].text)*0.01
      rang = float(self.xmlnode.xpath('BuildRefineCycle/RefmacResult/rmsANGLE')[-1].text)
      if rwrk > 0.5:    s = "the model is very incomplete or wrong"
      elif rwrk > 0.4:  s = "the model is substantially incomplete and may contain incorrect regions"
      elif rwrk > 0.35: s = "the model is likely to contain correct regions but requires further work"
      else:             s = "the model is approaching completion"
      parent.append( "<p>The refinement R-factor is %5.2f, and the free-R factor is %5.2f. The RMS bond angle deviation is %5.3f A.<br/>On the basis of the refinement statistics, %s.</p>"%(rwrk,rfre,rbnd,s) )
    except Exception,e:
      parent.append( "<p>Refinement results are not yet available.</p>" )

def test(xmlFile=None,jobId=None,reportFile=None):
  import sys,os
  if reportFile is None:
    if xmlFile is not None:
      reportFile = os.path.join(os.path.split(xmlFile)[0],'report.html')
    else:
      reportFile = os.path.join(os.getcwd(),'report.html')
  r = bucref_report(xmlFile=xmlFile,jobId=jobId)
  r.as_html_file(reportFile)
  if len(r.errorReport())>0: print 'ERRORS:',r.errorReport()
  # Temporary hard-wire to save typing..
  #r = bucref_report(xmlFile='/Users/lizp/Desktop/test_projects/t10/CCP4_JOBS/job_2/program.xml',jobId='1b86b099978d11e2822c3c0754185dfb')
  #r.as_html_file('/Users/lizp/Desktop/test_projects/t10/CCP4_JOBS/job_2/report.html')
"""
