#!/usr/bin/python
import os,sys
from program import program
import common

class afro(program):
  name="Afro"
  binary="afro"
  labelout_prefix="AFRO_"
  ccp4_parsing=True
  stat={}
  stat['version'] = common.stats(name='version', regexp=r"afro;\s+version\s+(\S+)")
  stat['ccp4_version'] = common.stats(name='version', regexp=r"CCP4 software suite: library version\s+(\S+)")
  references = ( "Pannu NS, Waterreus WJ,  Skubak P, Sikharulidze I, Abrahams JP & "+
                 "de Graaff RAG (2011) Recent advances in the CRANK software suite "+
                 "for experimental phasing. Acta Cryst. D67, 331-337.", )

  def Init(self):
    self.outfilename = { 'mtz': self.name+'.mtz' }

  def TreatInput(self):
    exper=self.GetKey('targ')
    obj,N=self.inp.GetTargetObjects(exper)
    if obj is None:
      common.Error('The input objects for target {0} of {1} could not be retrieved'.format(exper,self.name))
    # SAD input
    if exper=='SAD': 
      # crystal and dataset name are compulsory for Afro...
      self.SetKey('XTAL', obj['f+'].xname)
      self.SetKey('ATOM', obj['mod'].GetAtomType())
      if obj['mod'].exp_num_atoms:
        self.SetKey('NUMB', obj['mod'].exp_num_atoms)
      if self.process.IsNonFalseVirtPar('bfactor') and not self.GetKey('BISO'):
        self.SetKey( 'BISO', self.process.GetVirtPar('bfactor') )
      else:
        self.SetKey('BISO', 25)
      self.SetKey('DNAME', obj['f+'].dname)
      self.SetArg( 'hklin', obj['f+'].GetFileName('mtz') )
      self.SetKey(  'colu', ('F+='+obj['f+'].GetLabel('f'), 'SF+='+obj['f+'].GetLabel('sigf')) )
      self.AddToKey('colu', ('F-='+obj['f-'].GetLabel('f'), 'SF-='+obj['f-'].GetLabel('sigf')) )
      for at,f in obj['mod'].GetAtomTypes().iteritems():
        if f[0] is not None and f[1] is not None:
          self.SetKey('FORM', '{0} FP={1} FPP={2}'.format(at,f[0],f[1]))

  def TreatParams(self):
    if not self.GetKey('targ'):
      if self.process.GetVirtPar('target')=='SAD':
        self.SetKey('targ','SAD')
    else:
      self.CapitalizeKey('targ')
    program.TreatParams(self)

  def DefineOutput(self):
    xname=self.inp.Get('model').GetCrystalName()
    outmtz=self.outfilename['mtz']
    self.outfa = self.out.AddNew( 'fsigf', outmtz, typ='fa', xname=xname )
    self.outfa.SetLabel( ['f','sigf'] )
    self.outea = self.out.AddNew( 'fsigf', outmtz, typ='ea', xname=xname )
    self.outea.SetLabel( ['f','sigf'] )


  def TreatOutput(self):
    self.SetKey( 'labout',   ('FA='+self.outfa.GetLabel('f'), 'SGFA='+self.outfa.GetLabel('sigf')) )
    self.AddToKey( 'labout', ('EA='+self.outea.GetLabel('f'), 'SGEA='+self.outea.GetLabel('sigf')) )
    self.SetArg( 'hklout', self.outfa.GetFileName('mtz') )
    #self.SetArg( 'hklout', self.outea.GetFileName('mtz') )
    #self.SetArg( 'xyzout', self.outmodel.GetFileName('pdb') )
