#
#  Translate and BackTranslate - Convert Protein <-> DNA <-> RNA. 
#
#                                       Alexander Roth (Nov 3, 2005)
#

# Replace a phrase in a text. /AR
ReplaceString := proc(old:string, new:string, txt:string)
  tmptxt:=copy(txt);
  newtxt:='';
  lo:=length(old);
  do
    x:=SearchString(old, tmptxt);
    newtxt:=newtxt . tmptxt[1..x];
    if x=-1 then break fi;
    newtxt:=newtxt . new;
    tmptxt:=tmptxt[x+lo+1..-1];
  od;
  return(newtxt);
end:

# Transcribe DNA in to RNA. /AR
Transcribe := proc(dna:string)
  return(ReplaceString('T','U',dna));
end:

# (Back-)Transcribe RNA into DNA. /AR
BackTranscribe := proc(rna:string)
  return(ReplaceString('U', 'T', rna));
end:

# Translate DNA into protein. /AR
# with support for alternative codes. /ar
Translate := proc(dna:string ; alt=1:posint)
    if mod(length(dna),3)<>0 then
        error('length of seq is not divisable by 3') fi;
    prot:='';
    if nargs>1 then
        if AltGenCode(alt,'ATG')=0 then 
            error('the alternative code', alt,'is not available') fi;
        prot:=prot.AltGenCode(alt,dna[1..3])[-1];
        for i from 4 to length(dna) by 3 do
            prot:=prot.AltGenCode(alt,dna[i..i+2])[1];
        od;
    else
        for i to length(dna) by 3 do
            prot:=prot.CodonToA(dna[i..i+2]);
        od;
    fi;
    if prot[-1..-1]='$' then prot:=prot[1..-2] fi;
    prot
end:

#module external CodonCount, CodonUsage, BackTranslate;

# Count the codons in a database or a string. /AR
CodonCount := proc( ; d:string)
  global CodonCountsG, DBmarkG;
  Codons := CreateArray( 1..64 ):
  if nargs=0 then
    if not assigned(DB) then error('DB need to assigned, use ReadDb()') fi;
    if not assigned(CodonCountsG) or DBmarkG<>DB['TotChars'] then
      DBmarkG:=DB['TotChars'];
      for e in Entries() do
        d := SearchTag(DNA,string(e));
        for i to length(d) by 3 do
          cod:=CodonToCInt(d[i..i+2]);
          if cod=0 then next fi;   # to avoid XXX
          Codons[cod] := Codons[cod] + 1;
        od;
      od:
      CodonCountsG:=Codons;
    else
      Codons:=CodonCountsG;
    fi;
  else
    if mod(length(dna),3)<>0 then 
      error('length of seq is not divisable by 3') fi;
    d:=uppercase(d);
    for i to length(d) by 3 do
      cod:=CodonToCInt(d[i..i+2]);
      if cod=0 then next fi; # if seq contain X
      Codons[cod] := Codons[cod] + 1;
    od:
  fi;
  Codons;
end:

# Get codon usage for an organism or a string. /AR
CodonUsage := proc( ; da:string, opt={}:set(string))
  if assigned(da) then
    Codons:=CodonCount(da);
  else
    if not assigned(DB) then 
      error('CodonUsage reads from variable DB, use ReadDb()') fi;
    Codons:=CodonCount();
  fi;
  # normalize
  CC := CreateArray( 1..64 ):
  for i to 64 do
    s:=0;
    for ss in IntToCInt(CIntToInt(i)) do
      s:=s+Codons[ss];
    od;
    if s=0 then next fi;
    CC[i]:=Codons[i]/s;
  od:
  if member('list',opt) then return(CC) fi;
  # create a table of codonusage
  CT:=[];
  for i to 22 do
    if i=21 then CT:=append(CT,[['XXX', 1]]); next; fi;
    part:=[];
    for j in IntToCodon(i) do
      part:=append(part, [j, CC[CodonToCInt(j)]]);
    od;
    CT:=append(CT,part):
  od;
  # sort table according to frequency
  CodonTable:= CreateArray(1..22);
  for i to 22 do
    a:=CT[i];
    if length(a)>1 then
      CodonTable[i]:=sort(a, a-> -a[2]);
    else
      CodonTable[i]:=a;
    fi;
  od;
  return(CodonTable);
end:

# Count patterns in DB.  /AR
PatternCount := proc(k:posint, l:posint; ofs=1:posint)
  global PatternCountsG, DBmarkG;
  
  if printlevel>1 then lprint( 'l=',l, 'k=', k, 'ofs=', ofs) fi;
  if not assigned(DB) then error('DB need to assigned, use ReadDb()') fi;
  if not assigned(PatternCountsG) or 
    DBmarkG<>hash([DB[string],k,l,ofs]) then
    DBmarkG:=hash([DB[string],k,l,ofs]);
    
    Patterns := CreateArray( 1..4^k ):
    for e in Entries() do
      d := SearchTag(DNA,string(e));
      ld:=If(k>l,length(d)-k+2-l, length(d)-k+1);
      for i from ofs to ld by l do
        pat:=d[i..i+k-1];
        ind:=1;
        for j to length(pat) do
          ind:=ind + ( (BToInt(pat[-j])-1) * 4^(j-1));
        od;
        if cod=0 then next fi;   # to avoid X
        Patterns[ind] := Patterns[ind] + 1;
      od;
    od:
    PatternCountsG:=Patterns;  
  else
    Patterns:=PatternCountsG;
  fi;
  Patterns;
end:

# Get codon usage for an organism or a string. /AR
PatternUsage := proc( ; da:string, opt={}:set(string))
    if assigned(da) then
        Patterns:=PatternCount(da);
    else
        if not assigned(DB) then
            error('CodonUsage reads from variable DB, use ReadDb()') fi;
        Patterns:=PatternCount(da);
    fi;
    # normalize
    PC := CreateArray( 1..length(Patterns) ):
    ############################################### unfinished.........!
    for i to 64 do
        s:=0;
        for ss in IntToCInt(CIntToInt(i)) do
            s:=s+Codons[ss];
        od;
        if s=0 then next fi;
        CC[i]:=Codons[i]/s;
    od:
    if member('list',opt) then return(CC) fi;
    # create a table of codonusage
    CT:=[];
    for i to 22 do
        if i=21 then CT:=append(CT,[['XXX', 1]]); next; fi;
        part:=[];
        for j in IntToCodon(i) do
            part:=append(part, [j, CC[CodonToCInt(j)]]);
        od;
        CT:=append(CT,part):
    od;
    # sort table according to frequency
    CodonTable:= CreateArray(1..22);
    for i to 22 do
        a:=CT[i];
        if length(a)>1 then
            CodonTable[i]:=sort(a, a-> -a[2]);
        else
            CodonTable[i]:=a;
        fi;
    od;
    return(CodonTable);
end:



# Backtranslate a protein into DNA using several models. 
# Available models are:
#
#   Random  - Select codons randomly
#   Freq    - Select the most frequenct codons (default)
#   Least   - Select the least frequenct codons/motifs
#   Reuse   - Choose codons favoring reuse   ( to be implemented... )
#   DynProg - Select codons based on favoued motifs in in coding DNA
# 
# or any combination thereof.   ( work in progress... )
#
#                           Alexander Roth (Dec 2005)
#

BackTranslate := proc( tA:string ;
                       opt='Freq':{{'Random','Freq','Least','Reuse','DynProg'},
			set({'Random','Freq','Least','Reuse','DynProg'})},
		       tD:string,
		       db1:database, 
                       k:posint, l:posint, ofs:posint)

  opt:={op(opt)};   # if opt is string, make it a set
  ret:='';
 
  if member('DynProg', opt) then
    if nargs<3 then
      return( BackTranslateDP( tA ) );
    else
      return( BackTranslateDP( tA, args[3..-1]) );
    fi;
  fi;

  if length(opt)=1 and opt[1]='Random' then   # Only random
    for i to length(tA) do
      ret:=ret.Rand({op(AToCodon(tA[i]))});
    od;
    return(ret);  
  fi;

  if member('Freq',opt) or member('Least',opt) then
    
    if assigned(tD) then
      CodonTableG:=CodonUsage(tD);
    else
      CodonTableG:=CodonUsage();
    fi;

    for i to length(tA) do
      a:=AToInt(tA[i]);
      if a=0 then a:=21 fi;

      if member('Random', opt) then
        if length(CodonTableG[a])=1 then rc:=1
        else
          ccd:=transpose(CodonTableG[a])[2];
          for c from 2 to length(ccd) do ccd[c]:=ccd[c-1]+ccd[c] od;
          rc:=SearchOrderedArray(Rand(), ccd)+1;
        fi;
        temp:=CodonTableG[a, rc, 1];
      elif member('Least', opt) then
        temp:=CodonTableG[a, -1, 1];
      else
        temp:=CodonTableG[a, 1, 1];
      fi;
      ret:=ret.temp;
    od;
  fi;

  return(ret);
end:

#
#	Backtranslate a protein into bases using dynamic programming
#	to maximize the joint frequency of all the k-mers appearing
#	in the DNA sequence (their frequency as taken from DB or db1,
#	a DNA database).
#
#						Gaston H Gonnet(Dec 8, 2005)
#
#   Support for the frequency of any pattern.  It is likely that some are more
#   important for the efficeny of translation (for example the nucletides over
#   the codon border)
#
#                       Alexander Roth (Aug 9, 2006)
#
BackTranslateDP := proc( aas:string ; k=7:posint, l=1:posint, 
                        ofs=1:posint, db1:database)
  global DB;
  DBold := DB;
  if assigned(db1) then DB := db1
  elif not type(DB,database) then error('a database must be loaded') fi;
  
  if k > 14 then
    DB := DBold;
    error(k,'acceptable values of k are between 3 and 14' ) fi;
  
#  if l=1 then
#    if DB[type] <> 'DNA' then
#      testt:=SearchTag('DNA', Entry(1));
#      if type(testt,string) and length(testt)>0 then
#        fn:='temp'.string(DB[TotChars]).'.dna.db';
#        if length(FileStat(fn))<>14 then
#          OpenWriting(fn);
#          for e in Entries() do
#            printf('<E><ID>%s</ID><SEQ>%s</SEQ></E>\n',
#                   SearchTag('ID', e),
#                   SearchTag('DNA', e));
#          od;
#          OpenWriting(previous);
#        fi;
#        DB:=ReadDb(fn);
#      else
#        DB := DBold; error(DB,'database must contain DNA information') 
#      fi;
#   fi;
#  else
    Patterns:=PatternCount(k,l,ofs);
#  fi;
  
  pool := copy([['',0]]);
  i := 0;       # amino acid aas[i] is already in pool
                #   length(pool[..,1]) = 3*i
  j := k+ofs-2; # score of k-mers up to pool[..,1,j] has been added already
  
  while i < length(aas) or j < 3*i do
    if j < 3*i then
      
      # add the scores for the k-mer ending at j
      for z in pool do
        pat:=z[1,j-k+2..j+1];
        ind:=1;
        for lp to length(pat) do
          ind:=ind + ( (BToInt(pat[-lp])-1) * 4^(lp-1));
        od;
        m:=Patterns[ind];
        if m <= 0 then z[2] := -DBL_MAX
        else z[2] := z[2] + ln(m) fi
      od;
      
      j := j+l;
      
      # if there are duplicates within the last k-mer then
      # keep the one with the highest score only
      if j >= 3*i then
        pool := sort( pool, x -> [x[1,1-k..-1],-x[2]] );
        newp := [pool[1]];
        for ip from 2 to length(pool) do
          if pool[ip-1,1,1-k..-1] <> pool[ip,1,1-k..-1] then
            newp := append(newp,pool[ip]) fi
        od;
        pool := newp
      fi;
      
    # has to include a new amino acid: enlarge the pool of solutions
    else i := i+1;
      aa := AToInt(aas[i]);
      if aa=0 and aas[i]='$' then aa := 22 fi;
      if aa=0 or aa=21 then
        DB := DBold;
        error(aas[i],aas,'invalid amino acid in input sequence')
      fi;
      cods := IntToCodon(aa);
      if length(cods)=1 then
        for z in pool do z[1] := z[1] . cods[1] od
      else newp := [];
        for z in pool do
		  for w in cods do newp := append(newp,[z[1].w,z[2]]) od
        od;
        pool := newp;
      fi;
    fi;
  od;
  DB := DBold;
  sort(pool,x->x[2])[-1];
  # TODO: if there are more solutions with the same score at the end, take the 
  # most frequent pattern
end:

#end:  # end module

