import charite.christo.strap.StrapProtein;
import charite.christo.interfaces.*;
import charite.christo.strap.extensions.PairAlignerNeoBioPROXY;
import charite.christo.strap.extensions.MultipleAlignerClustalW;
import static java.lang.System.*;
import charite.christo.CacheResult;
/*
  java DemoSequenceAligner1
  This demo shows how proteins are aligned using automatic procedures.
  In STRAP are a few implementations of SequenceAligner.
  Most alignment methods can also align more than two sequences if
  getMaxNumberOfSequences() returns a number larger than two.
*/
public class DemoSequenceAligner1 {
    public static void main(String[] argv){

        /* Enable cache */
        CacheResult.setEnabled(true);

        final byte[][] seqs={
            "ASDFGHKL".getBytes(),
            "TEYGKL".getBytes(),
            "ATDYGHKL".getBytes(),
        };
        /* Make an instance and set the sequences */
        final SequenceAligner aligner=new MultipleAlignerClustalW();
        aligner.setSequences(seqs);
        /* First start computation, then retrieve the result. */
        aligner.compute();
        final byte[] ss[]=aligner.getAlignedSequences();

        /* Some alignment methods can cluster similar sequences together */
        /* This information is obtained with the following method: */
        final int[] order= aligner instanceof SequenceAlignerSorting ? ((SequenceAlignerSorting)aligner).getIndicesOfSequences() : null;

        out.println();
        for(int i=0;i<ss.length;i++) {
            if (order!=null) out.print(order[i]+" ");
            out.println(" "+new String(ss[i]));
        }
        /* Save result cache */
        CacheResult.save();
        System.exit(0);
    }
}


import charite.christo.interfaces.SequenceBlaster;
import charite.christo.interfaces.HasControlPanel;
import charite.christo.strap.extensions.Blaster_ebi_ac_uk;
import charite.christo.strap.extensions.Blaster_local_Wu;
import charite.christo.strap.extensions.Blaster_local_NCBI;
import charite.christo.ByteArray;
import charite.christo.blast.BlastResult;
import java.util.*;
import javax.swing.*;
import java.io.*;
import static java.lang.System.*;
import charite.christo.CacheResult;

/**
   java DemoSequenceBlaster

   This demo shows how Blast is used to find sequences that are similar
   to a given Sequence.  For performing large numbers of Blast runs
   please use the locally installed Blast rather than a web service.

*/
public class DemoSequenceBlaster {
    public static void main(String[] argv) throws Exception {

        /* The cache is located in ~/.StrapAlign/cached/ */
        CacheResult.setEnabled(true);

        /* Initialize a SequenceBlaster one of the following:
           Blaster_ebi_ac_uk, Blaster_local_Wu, Blaster_local_NCBI */

        final SequenceBlaster blaster=new Blaster_ebi_ac_uk();

        /*For a local blast installation an environment variable is pointing to
          the directory with databases.  */
        if (blaster instanceof Blaster_local_NCBI) out.println(" Variable BLASTDB="+System.getenv("BLASTDB"));
        if (blaster instanceof Blaster_local_Wu) out.println(" Variable WUBLASTDB="+System.getenv("WUBLASTDB"));

        blaster.setAAQuerySequence("KVFFKAGLLGLLEEMRDDKLAEIITATQARCRGFLM");

        out.print("The following databases are available: "+Arrays.asList(blaster.getAvailableDatabases()));

        /* Show A control panel to watch log messages */
        if (blaster instanceof HasControlPanel) {
            final JFrame f=new JFrame();
            f.setSize(300,300);
            f.getContentPane().add(((HasControlPanel)blaster).getControlPanel());
            f.show();
        }
        blaster.setDatabase("pdb");

        /* If this was already computed, then it might be in the cache. */
        final ByteArray xmlFromCache=blaster.getResultXml();
        final ByteArray xml;

        if (xmlFromCache==null) {
            /* computation takes a lot of time */
            blaster.compute();
            xml=blaster.getResultXml();
        } else xml=xmlFromCache;

        try {
            xml.write(new FileOutputStream(new File("output.xml")));
            out.println("The xml result is found in the file output.xml");
        } catch(IOException ioex) { out.println("Writing blast result: "+ioex); }

        /* BlastResult is an object oriented model of the Blast Result  */
        final BlastResult result=new BlastResult(xml);

        try {
            final int charactersPerLine=60;
            result.writeFile(new File("output.txt"), charactersPerLine);
            out.println("The result is found in the file output.txt");
        } catch(IOException ioex) { out.println("Writing blast result: "+ioex); }

        /* The cache is saved to disk and the  Java Virtual Machine terminated */
        /* Save the Cache containing computed results */
        CacheResult.save();
        System.exit(0);
    }
}


import charite.christo.strap.extensions.*;
import charite.christo.strap.extensions.SecondaryStructure_Jnet;
import charite.christo.strap.extensions.SecondaryStructure_NNPREDICT;
import charite.christo.strap.extensions.SecondaryStructure_Sopma;
import charite.christo.strap.extensions.CoiledCoil_PredictorRobinson;
import charite.christo.strap.extensions.TransmembraneHelix_Phobius;
import charite.christo.strap.extensions.TransmembraneHelix_MEMSAT;

/* ... There are many more int the package ... charite.christo.strap.extensions. */

import charite.christo.interfaces.SecondaryStructure_Predictor;
import charite.christo.interfaces.TransmembraneHelix_Predictor;
import charite.christo.interfaces.CoiledCoil_Predictor;
import charite.christo.interfaces.PredictionFromAminoacidSequence;
import charite.christo.Web;
import charite.christo.CacheResult;
/*
  java   DemoPrediction
  Secondary structure elements like helices and beta sheets can be predicted from the primary structure.

  Three interfaces are derived from PredictionFromAminoacidSequence for secondary structures, coiled-coils and
  transmembrane helices.
*/
public class DemoPrediction {
    public static void main(String[] argv){
        /* The cache is located in ~/.StrapAlign/cached/ */
        CacheResult.setEnabled(true);

        /*Create an instance of SecondaryStructure_Predictor */
         PredictionFromAminoacidSequence predictor=new SecondaryStructure_NNPREDICT();
        /* Set the sequence. */
        /* The setter allows also multiple sequences given as an array of Strings. */
        /* This improves performance for web based methods and allows some methods to compute the consensus. */
        predictor.setGappedSequences(new String[]{"MFLTRSEYDRGVNTFSPEGRLFQVEYAIEGHKLGSTAIGIQTSEGVCLAVEKRITSPLMEPSSIEKIVEIDAHIGCAMSGLIADAKTLIDKARVETQNHWFTYNETMTVESVTQAVSNLALQFGEEDADPGAMSRPFGVALLFGGVDEKGPQLFHMDPSGTFVQCDARAIGSASEGAQSSLQEVYHKSTTLKEAIKSSLIILKQVMEEKLNATNIELATVQPGQNFHMFTKEELEEVIKDMEILCEDNTSLSSIPNSLMQVDGDSGLYRNDFNSRDANSSDASNWTIDGENRTNLSFEGYLPPTCLSILHLQEKNWSALLTAVVIILTIAGNILVIMAVSLEKKLQNATNYFLMSLAIADMLLGFLVMPVSMLTILYGYRWPLPSKLCAVWIYLDVLFSTASIMHLCAISLDRYVAIQNPIHHSRFNSRTKAFLKIIAVWTISVGVSMPIPVFGLQDDSKVFKQGSCLLADDNFVLIGSFVAFFIPLTIMVITYFLTIKSLQKEATLCVSDLSTRAKLASFSFLPQSSLSSEKLFQRSIHREPGSYTGRRTMQSISNEQKACKVLGIVFFLFVVMWCPFFITNIMAVICKESCNEHVIGALLNVFVWIGYLSSAVNPLVYTLFNKTYRSAFSRYIQCQYKENRKPLQLILVNTIPALAYKSSQLQAGQNKDSKEDAEPTDNDCSMVTLGKQQSEETCTDNINTVNEKVSCVDKQKELDSKVRNVKDKVMCIEHEIKSLEDLQDEYDFKCKTLQNREHLLLKKMYLMLDNKRKEVVHKIIELLNVTELTQNALINDELVEWKRRQQSACIGGPPNACLDQQNWFTIVAESLQQVRQQLKKLEELEQKYTYEHDPITKNKQVLWDRTFSLFQQLIQSS"});
        /* start computation */
        predictor.compute();
        /* get the result for the first and only sequence (index 0) */
        char result[]=predictor.getPrediction()[0];
       System.out.println(new String(result));

       /* Save the Cache containing computed results */
       CacheResult.save();
       System.exit(0);
    }
}


import charite.christo.strap.*;
import static java.lang.System.*;
/*
  java   DemoProtein_aminoAcids
  This demo shows how protein objects are created.
*/
public class DemoProtein_aminoAcids {
    public static void main(String argv[]) {
        /* Make a protein instance. */
        /* The null in the constructor denotes that we do not need a reference to an StrapAlign object. */
        /* However, within the graphical program STRAP all proteins contain a reference to the StrapAlign object. */
        final StrapProtein p=new StrapProtein();
        /* give the protein a name */
        p.setName("myName");
        /* The  methods accepting strings as argument are convenient but slower than the byte array based methods */
        p.setResidueType("ASDFGHKL");
        /* Retrieve the residue type using the fast and inconvenient way */
        final byte[] resTyp=p.getResidueType();
        out.println("The sequence is="+new String(resTyp,0,p.countResidues()));
        /* NOTE: new String(resTyp) is not correct because the byte array  might exceed the number of residues. */
        /* The number of bytes converted to String must be limited by countResidues(). */
        /* The following is more convenient but more time consuming: */
        out.println("The sequence is "+p.getResidueTypeAsString());
        /* What are the coordinates in proteins defined only from  sequences? */
        /* Undefined fields of the  protein object are null. */
        /* In the present case the 3D coordinates are null. */
        out.println("The c-Alpha coordinates are not set. What will the get-method return?");
        out.println("p.getResidueCalpha()="+p.getResidueCalpha());
        exit(0);
    }
}


import charite.christo.strap.*;
import static java.lang.System.*;
/*
  java  DemoProtein_nucleotides
  This demo shows how protein objects are created from nucleotides.
  The amino acid sequence is translated from a nucleotide sequence.
  The nucleotide sequence may be the forward or the reverse complement strand.
  Genomic sequences contain translated and untranslated regions such as
  introns, 3'UTRs and 5'UTRs.
  The translated nucleotide indices are true-values in  a boolean array.
*/
public class DemoProtein_nucleotides {
    public static void main(String argv[]) {
        final StrapProtein p= new StrapProtein();
        /* Initialize a protein instance with a nucleotide sequence and specify the direction of translation */
        p.setNucleotides("CCCACCCCACTT",StrapProtein.FORWARD); 
        out.println("The NT sequence is "+p.getNucleotidesCurrentStrandAsString());
        out.println("The AA sequence is "+p.getResidueTypeAsString());
        out.println();
        /* try reverse complement */
        out.println("translate reverse complement");
        p.setNucleotides("CCCACCCCACTT",StrapProtein.REVERSE_COMPLEMENT); 
        out.println("The NT sequence is "+p.getNucleotidesCurrentStrandAsString());
        out.println("The AA sequence is "+p.getResidueTypeAsString());
        out.println();
        /* Now coding and non-coding regions come into play */
        out.println("Only base 4,5 and 6 is coding for amino acids. The remaining NTs are non-coding ");
        p.setNucleotidesCurrentStrandTranslated(new boolean[]{false,false,false,true,true,true});
        out.println("The NT sequence is "+p.getNucleotidesCurrentStrandAsString());
        out.println("The AA sequence is "+p.getResidueTypeAsString());
        exit(0);
    }
}


import charite.christo.strap.StrapProtein;
import static java.lang.System.*;
/*
  java   DemoProtein_gaps
  Gaps are used to align proteins.
  They account for inserts and deletions during evolution.
  This demo shows several ways how gaps are introduced in protein objects.
*/
public class DemoProtein_gaps {
    public static void main(String argv[]) {
        final StrapProtein p= new StrapProtein();
        p.setName("myName");
        p.setResidueType("ASDFG");
        out.println("There are several ways how gaps can be added to a sequence:");
        out.println();
        p.setResidueGap(3,2);
        out.println("p.setResidueGap(3,2) results in " +p.getGappedSequenceAsString());
        out.println();
        p.setResidueGap(new int[]{0,0,2,0,0});
        out.println("p.setResidueGap(new int[]{0,0,2,0,0}) results in " +p.getGappedSequenceAsString());
        out.println();
        p.setGappedSequence("AS  DFG");
        out.println("p.setGappedSequence(\"AS  DFG\"); results in " +p.getGappedSequenceAsString());
        out.println();
        /* The method applyGappedSequence infers the gaps from a given gapped sequence. */
        /* Any non-letter is a gap. What letters are used does not matter.  */
        p.inferGapsFromGappedSequence("AAAA A".getBytes());
        out.println("p.inferGapsFromGappedSequence(\"AAAA A\"); results in " +p.getGappedSequenceAsString());
        out.println();
        /* The residue column gives the horizontal position of a residue */
        out.println("The residue column is larger than the residue index when there are gaps:");
        out.println("getResidueColumn(3)="+p.getResidueColumn(3));
        out.println("getMaxColumn() is the total length minus 1: "+p.getMaxColumn());
        exit(0);
    }
}


import charite.christo.strap.StrapProtein;
import static java.lang.System.*;
/*
  java  DemoProtein_userObjects
  This demo shows how objects are added and retrieved to proteins with
  the methods putClientProperty and getClientProperty.  The same
  methods exist for javax.swing.JComponent.
*/
public class DemoProtein_userObjects {
    public static void main(String argv[]) {
        StrapProtein p= new StrapProtein();
       out.println("I add an object using the key \"myKey\"");
        /* Associates the String object to the key "myKey" */
        p.putClientProperty("myKey","this is my object");
        /* Gets the object */
       out.println("client property="+p.getClientProperty("myKey"));
        /* A value null removes the property */
       out.println("I remove the  object ");
        p.putClientProperty("myKey",null);
        /* There is no value linked to the key "myKey" any more and the following should return null. */
       out.println("client property="+p.getClientProperty("myKey"));
    }
}


import charite.christo.strap.StrapProtein;
import charite.christo.protein.PDB_Parser;
import charite.christo.protein.ProteinWriter1;
import charite.christo.interfaces.ProteinWriter;
import charite.christo.protein.ProteinParser;
import charite.christo.ByteArray;
import static java.lang.System.*;
/*
  java   DemoResidueSubset hs_EscherichiaColi.pdb
  Terminal parts of a protein can be cut off, providing
  the beginning  and the end position of the segment of interest.
  The residues  of interest are given as a String expression:  "10-13".
  The residues do not need to be consecutive, and comma separated expressions are possible. 
  For referring to pdb-residue number and pdb-chains use the Rasmol syntax: number-colon-chain.
*/
public class DemoResidueSubset {
    public static void main(String argv[]) {
        /* Usually only cAlpha atoms are read. Here we are also interested in side chain atoms. */
        final StrapProtein p= StrapProtein.newInstance(new java.io.File(argv[0]),ProteinParser.SIDE_CHAIN_ATOMS);
        out.println("10-13 means residues 10,11,12,13");
        /* The following expressions are equivalent:  10,11,12,13 or   10-12,13  */
        /* For PDB structures you can also refere to the PDB-number and chain: 10:A-13:A */
        p.setResidueSubset("10-13");
        final ProteinWriter pw=new ProteinWriter1();
        final long mode=ProteinWriter.PDB|ProteinWriter.ATOM_LINES|ProteinWriter.SIDE_CHAIN_ATOMS;
        final ByteArray sb=new ByteArray("Seq=").append(p.getResidueType()).append("\n").append(p.getResidueType()).append("\n");
        pw.toText(p,null,mode,sb);
        out.println("\n\n"+sb);
        exit(0);
    }
}


import charite.christo.strap.StrapProtein;
import static java.lang.System.*;
/*
  java  DemoProtein_gaps_advanced
  It shows how residue positions of the gapped sequence are converted
  to residue indices of the ungapped sequence and vice-versa.
*/
public class DemoProtein_gaps_advanced {
    public static void main(String argv[]) {
        final StrapProtein p= new StrapProtein();
        p.setName("myName");
        p.setGappedSequence("AS   DFG");
        final int nColumns=p.getMaxColumn()+1;
        out.println("the gapped sequence has a length of "+nColumns);
        final int nRes=p.countResidues();
        out.println("the number of residues is  "+nRes);
        out.println();
        out.println("getGappedSequence()="+p.getGappedSequenceAsString());
        out.println();
        out.println("You can obtain the gap and column for each residue");
        out.println("In a sequence without gaps the residue gap is zero at each position and ");
        out.println("the residue column equals to the residue index.");
        out.println("The gap values indicate the amount of white space left from a residue.");
        out.println("getResidueGap()="+concat(p.getResidueGap(),nRes));
        out.println("getResidueColumn()="+concat(p.getResidueColumn(),nRes));
        out.println("getResidueColumn(2)="+p.getResidueColumn(2));
        out.println("return value of -1 in case of invalid indices: p.getResidueColumn(9)="+p.getResidueColumn(9));
        out.println();
        out.println("You can convert columns into residue indices");
        out.println("But what happens when the specified position has a gap and not a letter");
        out.println("as is the case for  position 3?");
        out.println("column2nextIndex(3)="+p.column2nextIndex(3));
        out.println("column2thisOrPreviousIndex(3)="+p.column2thisOrPreviousIndex(3));
        out.println("But p.column2index(3)="+p.column2index(3));
        out.println();
        out.println("You can get all values as an array:");
        out.println("columns2indices()="+concat(p.columns2indices(),nColumns));
        out.println("column2nextIndex()="+concat(p.columns2nextIndices(),nColumns));
    }
    /* print the first num fields of the array */
    private static StringBuffer concat(int ii[],int num) {
        final StringBuffer sb=new StringBuffer();
        for(int i=0;i<Math.min(num,ii.length);i++) {
            sb.append(ii[i]).append(" ");
        }
        return sb;
    }
}


import charite.christo.strap.*;
import static java.lang.System.*;
/*
  java  DemoProtein_nucleotides_advanced
  This demo shows advanced features of proteins
  translated from nucleotide sequences.
*/
public class DemoProtein_nucleotides_advanced {
    public static void main(String argv[]) {
        final StrapProtein p=new StrapProtein();
        out.println("Translate reverse complement");
        p.setNucleotides("CCCACCCCACTT",StrapProtein.REVERSE_COMPLEMENT);
        /* The original strand and the translated (current) strand are distinguished. */
        /* The original strand is CCCACCCCACTT. */
        /* The current strand is identical or the reverse complement AAGTGGGGTGGG. */
        /* This depends on the parameters reverse and complement of the setNucleotides-method. */
        out.println("The original NT sequence is "+p.getNucleotidesAsString());
        out.println("The NT sequence of current strand is "+p.getNucleotidesCurrentStrandAsString());
        out.println("The AA sequence is "+p.getResidueTypeAsString());
        out.println();
        out.println("You can request nucleotides at any position in the original or the current strand");
        out.println("getNucleotide(2)="+(char)p.getNucleotide(2));
        out.println("getNucleotideCurrentStrand(2)="+(char)p.getNucleotideCurrentStrand(2));
        out.println();
        /* By default all nucleotides code amino acids. */
        /* But the coding nucleotides can be set explicitly.*/
        out.println("The nucleotides 3, 4 and 5 are  coding. AAG => Tryptophan");
        p.setNucleotidesCurrentStrandTranslated(new boolean[]{false,false,false,true,true,true});
        out.println("The NT sequence is "+p.getNucleotidesCurrentStrandAsString());
        /* The three coding nucleotides make only one amino acid */
        out.println("The AA sequence is "+p.getResidueTypeAsString());
        out.println();
        /* There are four sequence: */
        /*   1. The original nucleotide sequence */
        /*   2. The nucleotide sequence of the current strand. */
        /*      Usually the same or the reverse-complement of the original one. */
        /*   3. The coding nucleotide sequence. The length can be divided by 3  */
        /*   4. The amino acid sequence. */
        /* The following demonstrates conversion of the coordinates. */
        out.println("You can convert  indices of the current strand to indices of the coding sequence");
        out.println("This is like conversion beteen genomic and mRNA positions");
        out.println("nucleotideIndices2translatedNucleotideIndices()="
                    +concat(p.nucleotideIndices2translatedNucleotideIndices(),p.countNucleotides())
                    +"  ( -1 means not translated)");
        out.println("translatedNucleotideIndices2nucleotideIndices()="
                    +concat(p.translatedNucleotideIndices2nucleotideIndices(),p.countCodingNucleotides()));
        out.println();
        out.println("You can convert indices of the current strand to indices of amino acids");
        out.println("nucleotideIndex2aminoAcidIndex(6)="+p.nucleotideIndex2aminoAcidIndex(6));
        out.println("aminoAcidIndex2nucleotideIndex(2)="+p.aminoAcidIndex2nucleotideIndex(2));
    }
    private static StringBuffer concat(int ii[],int count) {
        final StringBuffer sb=new StringBuffer();
        for(int i=0;i<Math.min(count,ii.length);i++)
            sb.append(ii[i]).append(" ");
        return sb;
    }
}


import charite.christo.strap.*;
import java.io.File;
import static java.lang.System.*;
/*
  java   DemoProtein_residueSets a1_SaccharomycesCerevisiae.pdb
  This demo shows how to convert an expression residue positions into a boolean array.
  Example:   1-3,5-6 ==>  XXX.XXX....
  If the number is followed by a colon, then the PDB-residue positions is used.
  Example 4:A is the residue of chain A with the PDB-number 4
*/
public class DemoResidueSubset2 {
    public static void main(String argv[]) {
        /* Make a protein instance. */
        final int OFFSET=1;
        final StrapProtein p= StrapProtein.newInstance(new File(argv[0]));
        {
            final String s="2-3,4,5,9";
            out.println(s+" ==> "+toString(p.residueSubsetAsBooleanArray(s,OFFSET)));
        }
        {
            /* You can also refere to the pdb residue number and chain. */
            final String s="2:A-3:A,4:A,5:A,9:A";
            out.println(s+" ==> "+toString(p.residueSubsetAsBooleanArray(s,OFFSET)));
        }
        exit(0);
    }
    private static StringBuffer toString(boolean bb[]) {
        final StringBuffer sb=new StringBuffer(bb.length);
        for(boolean b:bb) sb.append(b ? 'X' : '.');
        return sb;
    }
}



import charite.christo.strap.StrapProtein;
import charite.christo.protein.ProteinParser;
import charite.christo.protein.Protein;
import charite.christo.ChUtils;
import charite.christo.ByteArray;
import java.util.ArrayList;
import java.io.File;
import static java.lang.System.*;
/*
  java  DemoProteinParser2 hs_EscherichiaColi.pdb
  Imagine your protein files have a format which is not supported by STRAP.
  This demo explains, how a protein parser can be implemented and used.

  The text is given in charite.christo.ByteArray.  It has similar
  features like java.lang.String or StringBuffer, but is faster and
  keeps a reference of the positions of line ends.  The byte array may
  be longer than the valid text.  The valid text starts at index
  getBegin() and ends at getEnd().
*/
public class DemoProteinParser2 {
    public static void main(String argv[]) {
        out.println("This is the protein file parsed with the built-in parsers ");
        final  StrapProtein p1= StrapProtein.newInstance(new java.io.File(argv[0]));
        out.println("p1.getResidueType()="+p1.getResidueTypeAsString());
        /* Create a protein object */
        final  StrapProtein p2=new StrapProtein();
        /* Reads the text of the file given by the first  command line parameter */
        /* Evaluates the text and set the amino acid sequence in the protein object */
        final long options=0;
        p2.setName("p2");
        p2.parse(ChUtils.readBytes(new File(argv[0])),new ProteinParser[]{new MyParser()},options);
        /* Check the amino acid sequence */
        out.println("\nThis is the same protein file parsed with the self-made parser");
        out.println("p2.getResidueType()="+p2.getResidueTypeAsString());
        exit(0);
    }

    static class MyParser implements ProteinParser {
        /* This is the self-made parser. It is rather stupid. */
        /* Irrespectively of the contents of the protein file text it sets the same amino acid sequence. */
        public boolean parse(Protein p, long options, ByteArray byteArray) {
            final int ends[]=byteArray.getLineEnds();
            final int begin=byteArray.getBegin();
            final int end=byteArray.getEnd();
            final byte[] text=byteArray.getBytes();
            out.println(" The text contains "+(end-begin)+" characters and "+ends.length+" lines.");
            p.setResidueType("HelloWorld");
            /* By  returning true it indicates that parsing was successful, */
            /* False would say that it is the wrong protein file type for this parser. */
            return true;
        }
    }
}


import charite.christo.strap.StrapProtein;
import charite.christo.strap.interfaces.AlignmentWriter;
import charite.christo.strap.ExportAlignment;
/*
  java   DemoAlignmentWriter
  The class ExportAlignment is an implementations of the interface AlignmentWriter.
  The alignment consists of proteins p0 and p1.
  Both proteins have a gapped sequence and a name which are used to produce an output in MSF-format.
*/
public class DemoAlignmentWriter {
    public static void main(String[] argv){
        /* Prepare proteins */
        final StrapProtein p0=new StrapProtein();
        final StrapProtein p1=new StrapProtein();
        p0.setGappedSequence("ASDFGHKL");
        p1.setGappedSequence("AS FGHKL");
        p0.setName("protein0");
        p1.setName("protein1");
        /* create an instance of AlignmentWriter */
        final AlignmentWriter alignmentWriter=new ExportAlignment();
        /* Set the proteins of the alignment */
        alignmentWriter.setProteins(p0,p1);

        final StringBuffer sb=new StringBuffer();
        /* obtain the MSF-text  */
        final long options=AlignmentWriter.MSF;
        alignmentWriter.getText(options,sb);
        System.out.println(sb);
        System.exit(0);
    }
}


import charite.christo.strap.StrapProtein;
import charite.christo.interfaces.ProteinWriter;
import charite.christo.protein.ProteinWriter1;
import charite.christo.ByteArray;
/*
  java DemoProteinWriter
  A ProteinWriter produces a text representation of a protein object.
  Here charite.christo.protein.ProteinWriter1 is used. It supports several formats.

  Since java.lang.StringBuffer exhibits limitations and performance problems,
  STRAP uses its own implementation of StringBuffer: ByteArray.
*/
public class DemoProteinWriter {
    public static void main(String argv[]) {
        /* Create a protein object with a short sequence */
        StrapProtein p=new StrapProtein();
        p.setResidueType("ASDFGHKL");
        p.setName("protein1");
        /* initialize a ProteinWriter instance with the protein instance */
        ProteinWriter proteinWriter=new ProteinWriter1();
        final long mode=ProteinWriter.FASTA;

        final ByteArray sb=new ByteArray(999);
        /* Append the text to the ByteArray */
        proteinWriter.toText(p,null,mode,sb);
        System.out.println(sb);
        System.exit(0);
    }
}


import charite.christo.strap.StrapProtein;
import charite.christo.strap.ProteinBackbone3D;
import javax.swing.JFrame;
import java.io.File;
/*
  java   DemoViewProteinBackbone hs_EscherichiaColi.pdb
  ProteinBackbone3D is only capable of displaying protein backbones.
  Pymol and Jmol, however can produce high quality 3D-graphics.
  Pymol can be started by pressing the Pymol button.
*/
public class DemoViewProteinBackbone {
    public static void main(String[] argv){
        /* make a protein instance from a PDB-file */
        final StrapProtein p=StrapProtein.newInstance(new File(argv[0]));
        /* make a ProteinBackbone3D instance and add the protein */
        final ProteinBackbone3D w=new ProteinBackbone3D(null,0);
        w.addProteins(p);
        /* View the ProteinBackbone3D 3D-visualization in a JFrame */
        final JFrame f=new JFrame();
        f.setSize(300,300);
        f.getContentPane().add(w);
        f.show();
    }
}


import charite.christo.strap.StrapProtein;
import charite.christo.strap.DrawGappedSequence;
import charite.christo.strap.ResidueAnnotation;
import charite.christo.protein.ShadingAA;
import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/*
  java DemoDrawGappedSequence
  The method DrawGappedSequence#paintComponent is used to draw the sequence into a JComponent.
*/
public class DemoDrawGappedSequence {
    private static StrapProtein p;
    public static void main(String[] argv){
        /* make a protein with a gapped sequence */
        p=new StrapProtein();
        p.setGappedSequence("ASDFGH        JKLQWERTZUIOyxcvbnmAAAAAAAACCCCCCCCCWWWWWWWWWWWWWWW");
        /* Add a green selection to the protein. The selection gets a reference to the protein. */
        ResidueAnnotation s=new ResidueAnnotation(p);
        p.addResidueSelection(s);
        /*  The selection spans residues 3 to 5. */
        /*  For PDB-structures you can give selections in rasmol-syntax. */
        s.setSelectedAminoacids("3-5");
        s.setColor(Color.GREEN);
        /* Display the sequence in a JPanel */
        /* It is necessary to overwrite the paintComponent method. */
        final JPanel panel=new JPanel(){
                final Point origin=new Point(0,0);
                /* Overwriting the paint-method */
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);// background
                    /* ShadingAA.CHEMICAL paints each residue depending on its chemical nature. */
                    /* If the secondary structure is given in the protein file (PDB-format, DSSP-format) */
                    /* then the amino acids can also be shaded according to secondary structure (last parameter=true). */
                    new DrawGappedSequence().draw(this,g,origin,p,ShadingAA.CHEMICAL,DrawGappedSequence.SHADE_SEC_STRU);
                }
                /* The JScrollPane needs to know the size of its child: */
                /*  The panel size depends on the font and the horizontal position (max. column) of the last residue. */
                @Override public Dimension getPreferredSize() {
                    final FontMetrics fm=getFontMetrics(getFont());
                    final int charA=fm.getAscent(),charD=fm.getDescent(),charW=fm.charWidth('X'),charH=charA+charD;
                    return new Dimension(charW*(p.getMaxColumn()+1),charH);
                }
            };
        panel.setBackground(Color.BLACK);
        /* enlarge font */
        panel.setFont(new Font("Monospaced",Font.PLAIN,50));
        /* display it in a JFrame */
        final JFrame f=new JFrame();
        f.setSize(300,100);
        f.getContentPane().add(new JScrollPane(panel));
        f.show();
    }
}


import charite.christo.strap.StrapProtein;
import charite.christo.ByteArray;
import charite.christo.ChUtils;
import charite.christo.CacheResult;
import charite.christo.interfaces.ProteinWriter;
import charite.christo.interfaces.Superimpose3D;
import charite.christo.protein.Matrix3D;
import charite.christo.protein.PDB_Parser;
import charite.christo.protein.ProteinWriter1;
import charite.christo.strap.extensions.Superimpose3D_TM_align;
import java.io.File;
import static java.lang.System.*;
/*
  java  DemoSuperimpose1 a1_SaccharomycesCerevisiae.pdb hs_EscherichiaColi.pdb
  The protein hs_EscherichiaColi.pdb is superimposed on a2_SaccharomycesCerevisiae.
  The first protein (reference) is superimposed upon the 2nd (mobile) protein.
  The result is a transformation matrix for hs_EscherichiaColi.
  The proteins are not changed by the Superimpose3D class.
  But with the method Protein#setRotationAndTranslation(Matrix3D) the resulting
  transformation can be set to the protein.
*/
public class DemoSuperimpose1 {
    public static void main(String[] argv){

        /* The cache is located in ~/.StrapAlign/cached/ */
        CacheResult.setEnabled(true);

        /* prepare both protein objects */
        final StrapProtein pReference=StrapProtein.newInstance(new File(argv[0]));
        out.println("pReference="+pReference.getResidueTypeAsString());
        final StrapProtein pMobile=StrapProtein.newInstance(new File(argv[1]));
        out.println("pMobile="+pMobile.getResidueTypeAsString());
        /* Initialize the Superimpose3D object with the two proteins to be superimposed */
        final Superimpose3D_TM_align sup=new Superimpose3D_TM_align();
        sup.setMobileProtein(pMobile);
        sup.setReferenceProtein(pReference);
        /* start computation */
        sup.compute();
        /* Obtain the result */
        /* The Matrix3D object contains the coordinate transformation (rotation + translatio) */
        final Superimpose3D.Result result=sup.getResult();
        final Matrix3D transformation= result.toMatrix3D();

        /* Print the original coordinates of the mobile protein */
        final ByteArray sb=new ByteArray(100*1000)
            .append("*********************************************\n")
            .append("*** original *** \n");
        myPrint(pMobile,sb);
        /* Now change the coordinate system of the mobile protein and print the changed coordinates */
        pMobile.setRotationAndTranslation(transformation);
        sb.append("***  transformed *** \n");
        myPrint(pMobile,sb);
        out.println(sb);
        /* Save the Cache containing computed results */
        CacheResult.save();
        System.exit(0);
    }
    /* show only 3 amino acids */
    private static void myPrint(StrapProtein p,ByteArray sb) {
        final ProteinWriter pw=new ProteinWriter1();
        pw.selectResidues(new boolean[]{false,true,true});
        pw.toText(p,new Matrix3D[]{p.getRotationAndTranslation()},ProteinWriter.PDB|ProteinWriter.ATOM_LINES,sb);
    }
}


import charite.christo.strap.StrapProtein;
import charite.christo.strap.StrapProtein;
import charite.christo.strap.ResidueAnnotation;
import static java.lang.System.*;
import static charite.christo.ChConstants.*;
/*
  java   DemoResidueAnnotation
  Residue annotations associate text to  a set of residues.
  The text is an array of key value pairs.
*/
public class DemoResidueAnnotation {
    public static void main(String argv[]) {
        final StrapProtein p=new StrapProtein();
        p.setResidueType("ASDFGHKL");
        out.println("p.getResidueType()="+p.getResidueTypeAsString());
        final ResidueAnnotation annotation=new ResidueAnnotation(p);
        p.addResidueSelection(annotation);
        /* Text attributes like remarks can be added. */
        /* Beside REMARK several other type of text attributes exist. */
        /* Please see the STRAP manual for details. */
        annotation.setValue("Remark","a remark");
        /* The difference to a classical Map is that you can add a 2nd remark. */
        /* Using the key ResidueAnnotation.REMARK, both entries can be retrieved. */
        annotation.setValue("Remark","another remark");
        /* Specify the selected residues */
        /* Indices out of range are ignored. */
        annotation.setSelectedAminoacids("3-5,7,70-79,900-1000");
        /* print an "X" for selected and a dot for not selected. */

        printBool(annotation.getSelectedAminoacids(), annotation.getSelectedAminoacidsOffset());
        out.println();

        /* All residue selections can be retrieved from the protein object.*/
        /* In this example there is only one residue selection. */
        out.println("The number of ResidueAnnotation-objects in p is "+p.getResidueAnnotations().length);
        exit(0);
    }
    private static void printBool(boolean bb[],int offset) {
        for(int i=0;i<offset;i++) out.print('-');
        for(boolean b:bb) out.print(b ? "X" : ".");
    }

}


import charite.christo.strap.StrapProtein;
import charite.christo.strap.StrapProtein;
import charite.christo.strap.ResidueAnnotation;
import static java.lang.System.*;
/*
  java   DemoResidueAnnotation_NT
  Instead of specifying amino acid positions, nucleotides can be specified.
*/
public class DemoResidueAnnotation_NT {
    public static void main(String argv[]) {
        final StrapProtein p=new StrapProtein();
        p.setNucleotides("ACGGGGGAAAAAACCCCCTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT",StrapProtein.FORWARD);
        out.println("getNucleotides()="+p.getNucleotidesAsString());
        out.println("getNucleotidesCurrentStrand()="+p.getNucleotidesCurrentStrandAsString());
        out.println("getResidueType()="+p.getResidueTypeAsString());
        /* Creates a new residue selection with the given nucleotide positions. */
        final ResidueAnnotation annotation=new ResidueAnnotation(p);
        annotation.setSelectedNucleotides("3,7,10-11");
        p.addResidueSelection(annotation);
        /* Now print the selected nucleotides and selected amino acids. */
        /* "X" means selected and dot means not selected. */
        out.print("\n\nannotation.getSelectedNucleotides():");
        printBool(annotation.getSelectedNucleotides(),annotation.getSelectedNucleotidesOffset());
        /* An amino acid is selected when at least one of the three nucleotides of the triplet is selected. */
        out.print("\n\nannotation.getSelectedAminoacids():");
        printBool(annotation.getSelectedAminoacids(), annotation.getSelectedAminoacidsOffset());
        out.println();
        exit(0);
    }
    private static void printBool(boolean bb[],int offset) {
        for(int i=0;i<offset;i++) out.print('-');
        for(boolean b:bb) out.print(b ? "X" : ".");
    }
}


import charite.christo.strap.StrapProtein;
import charite.christo.strap.BiojavaSequence2StrapProtein;
import org.biojava.bio.seq.GappedSequence;
import org.biojava.bio.seq.ProteinTools;
import static java.lang.System.*;
/*
  java   DemoBiojavaSequence2StrapProtein
  If you want to add strap-functionality to your biojava project
  you might need to turn Biojava sequence objects into strap objects.
  BiojavaSequence2StrapProtein is a class that extends StrapProtein.
  Protein objects are  constructed with a Biojava gapped sequence object.
*/
public class DemoBiojavaSequence2StrapProtein {
    public static void main(String[] argv){
        try {
            /* prepare a Biojava GappedSequence-object for testing */
            GappedSequence gs=ProteinTools.createGappedProteinSequence("asdfgfghk","name");
            gs.addGapsInSource(3,10);
            out.println("gs.addGapsInSource(3,10); Inserts a gap after the 2nd and before the 3rd residue");
            out.println("In STRAP residue indices start with zero but in Biojava with one.");
            out.println(gs.seqString());

            /* conversion to Strap */
            StrapProtein p=new BiojavaSequence2StrapProtein(gs);
            /* check whether the sequence is OK */
            out.print("p.getResidueType()="+p.getResidueTypeAsString());
            out.print("p.getGappedSequence()="+p.getGappedSequenceAsString());
        } catch(Exception e){ e.printStackTrace(out);}
        exit(0);
    }
}


import charite.christo.strap.StrapProtein;
import charite.christo.strap.StrapProtein;
import charite.christo.strap.ResidueAnnotation;
import charite.christo.strap.StrapProtein2BiojavaSequence;
import charite.christo.strap.BiojavaSequence2StrapProtein;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import org.biojava.bio.gui.sequence.SequenceRenderer;
import org.biojava.bio.gui.sequence.FeatureRenderer;
import org.biojava.bio.gui.sequence.BasicFeatureRenderer;
import org.biojava.bio.gui.sequence.SymbolSequenceRenderer;
import org.biojava.bio.gui.sequence.SequencePanel;
import org.biojava.bio.gui.sequence.FeatureBlockSequenceRenderer;
import org.biojava.bio.gui.sequence.MultiLineRenderer;
import org.biojava.bio.symbol.RangeLocation;
import org.biojava.bio.seq.GappedSequence;
import org.biojava.bio.seq.ProteinTools;
/*
  java   DemoStrapProtein2BiojavaSequence
  Usage of the class StrapProtein2BiojavaSequence is demonstrated.
  A STRAP protein object with a gapped sequence and a residue selection is created
  and converted into Biojava object.
*/
public class DemoStrapProtein2BiojavaSequence {
    public static void main(String argv[]) {
        /* Initiate a STRAP protein object with a gapped sequence */
        final StrapProtein p=new StrapProtein();
        p.setGappedSequence("ASD   FGHKL");
        /* Add a residue selection to the STRAP protein */
        final ResidueAnnotation annotation=new ResidueAnnotation(p);
        annotation.setSelectedAminoacids("3-5,70-79,900-1000");
        p.addResidueSelection(annotation);
        /* Convert the STRAP object to BioJava */
        final GappedSequence biojavaSequence=new StrapProtein2BiojavaSequence(p).sequence();
        /* Display using BioJava-methods */
        showWithBiojava(biojavaSequence);
    }
    /* This method displays a Biojava object. */
    /* It uses exclusively  Biojava methods. */
    /* See the examples in "Biojava in Anger" by Mark Schreiber for more details. */
    private static void showWithBiojava(GappedSequence seq) {
        try{
            final MultiLineRenderer mlr=new MultiLineRenderer();
            final FeatureRenderer featr=new BasicFeatureRenderer();
            final SequenceRenderer seqR=new SymbolSequenceRenderer();
            final SequencePanel seqPanel=new SequencePanel();
            final FeatureBlockSequenceRenderer fbr=new FeatureBlockSequenceRenderer();
            fbr.setFeatureRenderer(featr);
            mlr.addRenderer(fbr);
            mlr.addRenderer(seqR);
            seqPanel.setRenderer(mlr);
            seqPanel.setSequence(seq);
            seqPanel.setRange(new RangeLocation(1,seq.length()+1));
            final JFrame f=new JFrame();
            f.setSize(300,300);
            f.getContentPane().add(new JScrollPane(seqPanel));
            f.show();
        } catch(Exception e){System.out.println("caught: "+e);e.printStackTrace(System.out);}
    }
}