# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 2.0
#
# The contents of this file are subject to the Mozilla Public License Version
# 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/2.0/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is OMA standalone.
#
# The Initial Developer of the Original Code is CBRG Research Group; 
# ETH Zurich; Switzerland.
# Portions created by the Initial Developer are Copyright (C) 2005-2013
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#   Christophe Dessimoz <cdessimoz@inf.ethz.ch>
#   Adrian Altenhoff <adrian.altenhoff@inf.ethz.ch>
#   Stefan Zoller <stefan.zoller@inf.ethz.ch>
#   Adrian Schneider <adrian.schneider@inf.ethz.ch>
#   Alexander Roth <alexander.roth@inf.ethz.ch>
#   Gaston Gonnet <gonnet@inf.ethz.ch>
#
# ***** END LICENSE BLOCK *****
module external WriteOrthoXML, XMLEscape;
local Grp2Id;

Grp2Id:=0;


XMLEscape := proc(s:string)
    # Search for escape characters in string.
    escape_chars := [['&', '&amp;'],
                     ['"', '&quot;'],
                     ['''', '&apos;'],
                     ['<', '&lt;'],
                     ['>', '&gt;']]:

    r := s:
    for e in escape_chars do
        r := ConcatStrings(SearchDelim(e[1], r), e[2]):
    od:

    return(r):
end:


WriteXMLHeader := proc(release:string ; notes:string)
    printf('<?xml version="1.0" encoding="UTF-8"?>\n');
    printf('<orthoXML xmlns="http://orthoXML.org/2011/" version="0.3" '.
        'origin="OMA standalone" originVersion="%s">\n', XMLEscape(release));
    if assigned(notes) then
        printf(' <notes>\n%s\n </notes>\n', notes);
    fi:
end:


GetBestIDs := proc(e)
    ac := SearchTag('AC',e);
    id := SearchTag('ID',e);
    if ac='' then 
        # not an exported genome. just report what is in ID as protId
        return([id,'','']);
    fi:
    prt := tra := []:
    do
        ens := MatchRegex('ENS[A-Z]{0,3}([TP])[0-9]{6,11}',ac);
        if length(ens)=0 then break fi:
        if ens[2]='P' then prt := append(prt, ens[1]);
        else tra := append(tra, ens[1]) fi:
        ac := length(ens[1])+ac;
    od:
    if length(prt)=0 then prt := [ac] fi:

    if length(id)<1000 then
        ens := MatchRegex('ENS[A-Z]{0,3}G[0-9]{6,11}',id);
    else 
        for curId in SearchDelim('; ',id) do
            ens := MatchRegex('ENS[A-Z]{0,3}G[0-9]{6,11}',curId);
            if length(ens)>0 then break fi;
        od:
    fi:
    if length(ens)>0 then id := ens[1] fi:

    return([seq(ConcatStrings(z, '; '),z=[prt,tra]), id]);
end:


WriteGeneRefs := proc()
    global DB:
    id := 0;
    for gNr to length(genomes) do 
        g := genomes[gNr];
        tax := GS[g,TAXONID];
        if tax='' then tax := string(-1) fi;
        rel := GS[g,'DBRELEASE'];
        if rel='' then rel := GS[g,'FileName'] fi:
        printf(' <species name="%s" NCBITaxId="%s">\n', XMLEscape(g), tax);
        printf('  <database name="%s" version="%s">\n', XMLEscape(g), XMLEscape(rel));
        printf('   <genes>\n');
        DB := DBs[gNr];
        for i to GS[g,TotEntries] do 
            id := id+1;
            if not GuessIdType=false then 
                refs := GetBestIDs(Entry(i));
            else
                refs := [IDtable[gNr,i], '', '']:
            fi:
            printf('    <gene id="%d" protId="%s"%s%s/>\n', id, 
                XMLEscape(refs[1]), 
                If(refs[2]<>'',sprintf(' transcriptId="%s"', XMLEscape(refs[2])),''), 
                If(refs[3]<>'',sprintf(' geneId="%s"', XMLEscape(refs[3])),''));
        od:
        printf('   </genes>\n  </database>\n </species>\n');
    od:
    printf(' <groups>\n');
end:

WriteOMAPairs := proc(VP:matrix, Goff:list(integer) )
    ns := length(VP); assert(length(VP[1])=ns);
    for i to ns do for j from i+1 to ns do
        nrs := [seq( z, z=Goff[i]+1..Goff[i+1]),
                seq( z, z=Goff[j]+1..Goff[j+1])];
        uf := UnionFind(nrs):
        for x1 to length(VP[i,j]) do for y1 in VP[i,j,x1] do
            union(uf, [Goff[i]+x1, Goff[j]+y1]);
        od od:
        for c in uf['Clusters'] do if length(c)>1 then
            p := CreateArray(1..2,[]):
            for z in c do 
                k := SearchOrderedArray(z-1, Goff):
                if k=i then p[1] := append(p[1], z);
                elif k=j then p[2] := append(p[2],z) ;
                else error('must not happen'); fi:
            od:
            printf('  <orthologGroup>\n');
            for k to 2 do 
                if length(p[k])>1 then printf('   <paralogGroup>\n') fi:
                for z in p[k] do printf('    <geneRef id="%d" />\n', z); od:
                if length(p[k])>1 then printf('   </paralogGroup>\n') fi:
            od:
            printf('  </orthologGroup>\n');
        fi od:
    od od:
end:

WriteOMAGroups := proc(M:matrix, Goff:list(integer) )
    ns := length(M[1]):
    for i to length(M) do
        printf('  <orthologGroup id="%s">\n', IdForGroup(i));
        for j to ns do if M[i,j]<>0 then
            printf('   <geneRef id="%d" />\n', Goff[j]+M[i,j]);
        fi od:
        printf('  </orthologGroup>\n');
    od:
end:

WriteOMAHClusterR := proc( grp; id:string, (indent=2):posint )
    inS := CreateString(indent);
    if type(grp,posint) then 
        printf('%s<geneRef id="%d"/>\n', inS, grp);
    elif op(0,grp)=OrthologousCluster then 
        printf('%s<orthologGroup %s>\n', inS,
            If(assigned(id),sprintf('id="%a"',id),''));
        printf('%s <property name="TaxRange" value="%s" taxid="%d"/>\n', 
            inS, XMLEscape(grp[1]), TaxonomyIdFromLevel(grp[1]));
        for z in grp[2..-1] do
            WriteOMAHClusterR( z, indent+1);
        od:
        printf('%s</orthologGroup>\n',inS);
    elif op(0,grp)=ParalogousCluster then
        printf('%s<paralogGroup>\n',inS);
        for z in grp do 
            WriteOMAHClusterR( z, indent+1);
        od:
        printf('%s</paralogGroup>\n',inS);
    else error('unexpected structure: '.string(op(0,grp))) fi:
end:

WriteXMLEnd := proc()
    printf(' </groups>\n</orthoXML>\n');
end:

InitStableIDs := proc(data) 
    external Grp2Id;
    Grp2Id := traperror(GenerateStableIDs(data));
    if Grp2Id=lasterror then
        warning('could not generateStableIDs for groups:\n '.string(lasterror));
        Grp2Id := 0;
    fi:
end:

IdForGroup := proc(i:posint)
    external Grp2Id;
    return( string(If(Grp2Id=0,i,Grp2Id[i])) );
end:

TaxonomyIdFromLevel := proc(level)
    getId := proc(level)
        tax := traperror(TaxonomyEntry(level)):
        if tax=lasterror then id := -1 else id := tax['id'] fi:
        return(id);
    end:

    if SpeciesTree='lineage' then
        return( remember(getId(level)) )
    else return(-1) fi:
end:


getParamsAsNotes := proc()
    params := []:
    for p in ['MinScore','LengthTol','StablePairTol','VerifiedPairTol',
        'MinSeqLen',If(DoHierarchicalGroups=true,'ReachabilityCutoff',NULL)] do
        params := append(params, sprintf('%s=%a',p,eval(symbol(p))));
    od:
    return(ConcatStrings(params, '; '));
end:

WriteOrthoXML := proc(data, fn:string ; (stableGroupIDs=false):boolean)
    
    NS := length(genomes):
    Goff := CreateArray(1..NS+1):
    for i to NS do Goff[i+1] := Goff[i] + GS[genomes[i],TotEntries] od:

    if stableGroupIDs then InitStableIDs(data) fi:
    
    verb := Set(printgc=false);
    OpenWriting(fn);
    WriteXMLHeader(OMA_STANDALONE_VERSION, getParamsAsNotes());
    WriteGeneRefs();
    if type(data,matrix(integer)) then 
        WriteOMAGroups(data,Goff);
    elif type(data, list(structure(anything,OrthologousCluster))) then
        for i to length(data) do
            WriteOMAHClusterR( data[i], IdForGroup(i) );
        od:
    else 
        WriteOMAPairs(data,Goff); 
    fi:
    WriteXMLEnd();
    OpenWriting(previous);
    Set(printgc=verb);
end:

end: #module
