repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
cobs | cobs-master/cobs/test/TestConservationSumAverage.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package test;
import gocAlgorithms.AverageScoreGenerator;
import java.io.File;
import java.util.Random;
import junit.framework.TestCase;
import covariance.algorithms.ConservationSum;
import covariance.algorithms.ScoreGenerator;
import covariance.datacontainers.Alignment;
public class TestConservationSumAverage extends TestCase
{
public void testAverage() throws Exception
{
Random random = new Random();
String runningDirectory = TestConservationSumAverage.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println(runningDirectory);
Alignment a = new Alignment("1", new File(runningDirectory + "pnase.txt"), true );
a = a.getFilteredAlignment(90);
ConservationSum cSum = new ConservationSum(a);
AverageScoreGenerator asg = new AverageScoreGenerator(cSum);
for( int x=0; x< 100; x++)
{
int startLeft = a.getNumColumnsInAlignment() / 4;
int endLeft= startLeft + random.nextInt(10) + 2;
int startRight = endLeft + random.nextInt(15);
int endRight = startRight + random.nextInt(10) + 2;
System.out.println(startLeft + " " + endLeft + " " + startRight + " " + endRight);
double score= asg.getScore(a, startLeft, endLeft, startRight, endRight);
double reimpScore = getReimplementedAverage(cSum, a, startLeft, endLeft, startRight, endRight);
System.out.println(score + " " + reimpScore);
assertEquals(score, reimpScore);
}
}
private static double getReimplementedAverage( ScoreGenerator sGen, Alignment a,
int startLeft, int endLeft, int startRight, int endRight ) throws Exception
{
double sum =0;
int n=0;
for( int x= startLeft; x <=endLeft; x++)
{
for( int y=startRight; y <=endRight; y++)
{
double score=sGen.getScore(a, x, y);
{
sum += score ;
n++;
}
}
}
return sum / n;
}
}
| 2,495 | 28.364706 | 123 | java |
cobs | cobs-master/cobs/test/TestResultsFileLine.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package test;
import gocAlgorithms.COBS;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import covariance.datacontainers.Alignment;
import covariance.datacontainers.PdbFileWrapper;
import covariance.parsers.PfamParser;
import covariance.parsers.PfamToPDBBlastResults;
import cobsScripts.ResultsFileLine;
import cobsScripts.WriteScores;
import utils.ConfigReader;
import junit.framework.TestCase;
public class TestResultsFileLine extends TestCase
{
/*
* This assumes WriteScripts has been run
*/
public void testPNormalize() throws Exception
{
File file = new File(ConfigReader.getCleanroom() + File.separator + "results" +
File.separator + "2OG-FeII_Oxy_5_COBS_UNCORRECTED.txt.gz");
List<ResultsFileLine> list = ResultsFileLine.parseResultsFile(file);
double sum =0;
HashMap<String, List<Double>> map = new HashMap<String,List<Double>>();
for( ResultsFileLine rfl : list )
{
sum += rfl.getScore();
addOne(map, rfl.getRegion1(), rfl.getScore());
addOne(map, rfl.getRegion2(), rfl.getScore());
}
double globalAverage = sum / list.size();
System.out.println("GLOBAL AVERAGE = " +globalAverage);
HashMap<String, Double> avMap = getAverageMap(map);
HashMap<String, Double> anotherAvMap = ResultsFileLine.breakByColumn(list);
assertEquals(anotherAvMap.size(), avMap.size());
for(String s : avMap.keySet())
{
System.out.println("Comparing " + s);
assertEquals(avMap.get(s), anotherAvMap.get(s),0.0001);
}
List<ResultsFileLine> normList = ResultsFileLine.getNormalizedList(list);
assertEquals(normList.size(), list.size());
assertEquals(
ResultsFileLine.getMedianAverageDistance(normList), ResultsFileLine.getMedianAverageDistance(list) );
for( int x=0; x < list.size(); x++)
{
ResultsFileLine rfl = list.get(x);
ResultsFileLine normedRFL = normList.get(x);
assertEquals(rfl.getRegion1(), normedRFL.getRegion1());
assertEquals(rfl.getRegion2(), normedRFL.getRegion2());
assertEquals(rfl.getAverageDistance(), normedRFL.getAverageDistance());
assertEquals(rfl.getMinDistance(), normedRFL.getMinDistance());
double expectedNormedScore = rfl.getScore()
- avMap.get(rfl.getRegion1()) * avMap.get(rfl.getRegion2())/ globalAverage;
System.out.println(expectedNormedScore + " " + normedRFL.getScore());
assertEquals(expectedNormedScore, normedRFL.getScore(), 0.00001);
}
}
private static HashMap<String, Double> getAverageMap( HashMap<String, List<Double>> map )
{
HashMap<String, Double> averageMap = new HashMap<String,Double>();
for( String key : map.keySet() )
{
List<Double> list = map.get(key);
double sum =0;
for(Double d : list)
sum+=d;
averageMap.put(key, sum / list.size());
}
return averageMap;
}
private static void addOne( HashMap<String, List<Double>> map, String key, double score )
{
List<Double> list = map.get(key);
if( list == null)
{
list = new ArrayList<Double>();
map.put(key,list);
}
list.add(score);
}
/*
* This assumes WriteScripts has been run
*/
public void testCobsScore() throws Exception
{
File file = new File(ConfigReader.getCleanroom() + File.separator + "results" +
File.separator + "2OG-FeII_Oxy_5_COBS_UNCORRECTED.txt.gz");
COBS cobs = new COBS();
List<ResultsFileLine> list = ResultsFileLine.parseResultsFile(file);
PfamParser parser =new PfamParser();
Alignment a= parser.getAnAlignment("2OG-FeII_Oxy_5");
HashMap<String, PfamToPDBBlastResults> pfamToPdbMap = PfamToPDBBlastResults.getAsMap();
PfamToPDBBlastResults toPDB = pfamToPdbMap.get("2OG-FeII_Oxy_5");
PdbFileWrapper fileWrapper = new PdbFileWrapper( new File( ConfigReader.getPdbDir() + File.separator + toPDB.getPdbID() + ".txt"));
HashMap<Integer, Integer> pdbToAlignmentNumberMap= WriteScores.getPdbToAlignmentNumberMap(a, toPDB, fileWrapper);
for(ResultsFileLine rfl : list)
{
double score =
cobs.getScore(a,
pdbToAlignmentNumberMap.get(TestNumberOfElements.getFirstElement(rfl.getRegion1(), toPDB.getChainId())),
pdbToAlignmentNumberMap.get(TestNumberOfElements.getSecondElement(rfl.getRegion1(), toPDB.getChainId())),
pdbToAlignmentNumberMap.get(TestNumberOfElements.getFirstElement(rfl.getRegion2(), toPDB.getChainId())),
pdbToAlignmentNumberMap.get(TestNumberOfElements.getSecondElement(rfl.getRegion2(), toPDB.getChainId())));
assertEquals(score, rfl.getScore(), 0.0001);
}
System.out.println("passed");
}
/*
* This assumes WriteScripts has been run
*/
public void testFileParse() throws Exception
{
File file = new File(ConfigReader.getCleanroom() + File.separator + "results" +
File.separator + "2OG-FeII_Oxy_5_COBS_UNCORRECTED.txt.gz");
List<ResultsFileLine> list = ResultsFileLine.parseResultsFile(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( file ))));
reader.readLine();
for( int x=0; x < list.size(); x++)
{
ResultsFileLine rfl = list.get(x);
String s= reader.readLine();
StringTokenizer sToken = new StringTokenizer(s, "\t");
assertEquals(rfl.getRegion1(), sToken.nextToken());
assertEquals(rfl.getRegion2(), sToken.nextToken());
assertEquals(rfl.getCombinedType(), sToken.nextToken());
assertEquals(rfl.getScore(), Double.parseDouble(sToken.nextToken()),0.00001);
assertEquals(rfl.getAverageDistance(), Double.parseDouble(sToken.nextToken()),0.00001);
assertEquals(rfl.getMinDistance(), Double.parseDouble(sToken.nextToken()),0.00001);
}
reader.close();
}
}
| 6,535 | 30.728155 | 133 | java |
cobs | cobs-master/cobs/test/TestMcBascAverage.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package test;
import gocAlgorithms.AverageMcBASC;
import gocAlgorithms.AverageScoreGenerator;
import java.io.File;
import java.util.Random;
import junit.framework.TestCase;
import covariance.algorithms.McBASCCovariance;
import covariance.datacontainers.Alignment;
public class TestMcBascAverage extends TestCase
{
public void testAverage() throws Exception
{
Random random = new Random();
String runningDirectory = TestConservationSumAverage.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println(runningDirectory);
Alignment a = new Alignment("1", new File(runningDirectory + "pnase.txt"), true );
a = a.getFilteredAlignment(90);
McBASCCovariance mcBasc = new McBASCCovariance(a);
AverageMcBASC aMcBasc = new AverageMcBASC(a);
AverageScoreGenerator asg = new AverageScoreGenerator(mcBasc);
for( int x=0; x< 100; x++)
{
int startLeft = a.getNumColumnsInAlignment() / 4;
int endLeft= startLeft + random.nextInt(10) + 2;
int startRight = endLeft + random.nextInt(15);
int endRight = startRight + random.nextInt(10) + 2;
System.out.println(startLeft + " " + endLeft + " " + startRight + " " + endRight);
double score= aMcBasc.getScore(a, startLeft, endLeft, startRight, endRight);
double reimpScore = getReimplementedAverage(mcBasc, a, startLeft, endLeft, startRight, endRight);
System.out.println(score + " " + reimpScore);
assertEquals(score, reimpScore,0.0001);
assertEquals(score, asg.getScore(a, startLeft, endLeft, startRight, endRight),0.0001);
}
}
private static double getReimplementedAverage( McBASCCovariance mcBascm, Alignment a,
int startLeft, int endLeft, int startRight, int endRight ) throws Exception
{
double sum =0;
int n=0;
for( int x= startLeft; x <=endLeft; x++)
{
for( int y=startRight; y <=endRight; y++)
{
double score=mcBascm.getScore(a, x, y);
//if( score != McBASCCovariance.NO_SCORE && ! Double.isInfinite(score) && ! Double.isNaN(score))
{
sum += score ;
n++;
}
}
}
return sum / n;
}
}
| 2,758 | 29.318681 | 123 | java |
cobs | cobs-master/cobs/test/TestMcBasc.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package test;
import java.util.ArrayList;
import java.util.List;
import utils.MapResiduesToIndex;
import utils.Pearson;
import utils.TTest;
import covariance.algorithms.McBASCCovariance;
import covariance.datacontainers.Alignment;
import covariance.datacontainers.AlignmentLine;
import junit.framework.TestCase;
public class TestMcBasc extends TestCase
{
public void test1() throws Exception
{
List<AlignmentLine> list = new ArrayList<AlignmentLine>();
list.add(new AlignmentLine("1", "AA") );
list.add(new AlignmentLine("2", "GG") );
list.add(new AlignmentLine("3", "HH") );
int[][] metric = McBASCCovariance.getMaxhomMetric();
List<Double> sumList = new ArrayList<Double>();
sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('A')][MapResiduesToIndex.getIndex('A')]));
sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('A')][MapResiduesToIndex.getIndex('G')]));
sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('A')][MapResiduesToIndex.getIndex('H')]));
sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('G')][MapResiduesToIndex.getIndex('A')]));
sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('G')][MapResiduesToIndex.getIndex('G')]));
sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('G')][MapResiduesToIndex.getIndex('H')]));
sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('H')][MapResiduesToIndex.getIndex('A')]));
sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('H')][MapResiduesToIndex.getIndex('G')]));
sumList.add( new Double (metric[ MapResiduesToIndex.getIndex('H')][MapResiduesToIndex.getIndex('H')]));
Alignment a = new Alignment( "a", list );
McBASCCovariance mcBasc = new McBASCCovariance( a );
System.out.println( new Double (metric[ MapResiduesToIndex.getIndex('A')][MapResiduesToIndex.getIndex('G')]));
System.out.println( mcBasc.getAverages()[0] );
System.out.println( mcBasc.getSds()[0] );
System.out.println("Final score for this algorithm and the two test columns is: " + mcBasc.getScore(a, 0, 1));
assertEquals( mcBasc.getAverages()[0], TTest.getAverage(sumList), 0.001);
assertEquals( mcBasc.getAverages()[1], TTest.getAverage(sumList), 0.001);
assertEquals( mcBasc.getSds()[0], TTest.getStDev(sumList), 0.001);
assertEquals( mcBasc.getSds()[1], TTest.getStDev(sumList), 0.001);
}
public void testPerfectConservation() throws Exception
{
List<AlignmentLine> list = new ArrayList<AlignmentLine>();
list.add(new AlignmentLine("1", "AG") );
list.add(new AlignmentLine("2", "AG") );
list.add(new AlignmentLine("3", "AG") );
int[][] metric = McBASCCovariance.getMaxhomMetric();
Alignment a = new Alignment( "a", list );
McBASCCovariance mcBasc = new McBASCCovariance( a );
System.out.println( new Double (metric[ MapResiduesToIndex.getIndex('A')][MapResiduesToIndex.getIndex('G')]));
System.out.println( mcBasc.getAverages()[0] );
System.out.println( mcBasc.getSds()[0] );
Double finalScore = mcBasc.getScore(a, 0, 1);
System.out.println("Final score for this perfectly conserved algorithm and the two test columns is: " + finalScore);
Double expectedScore = 1.0;
assertEquals(expectedScore,finalScore);
}
public void testAgainstReimplementation( ) throws Exception
{
int[][] metric = McBASCCovariance.getMaxhomMetric();
List<AlignmentLine> list = new ArrayList<AlignmentLine>();
for( int x=0; x < 100; x++)
list.add(new AlignmentLine("" + x, TestCobs.getRandomProtein(2)));
Alignment a= new Alignment("Test", list);
double fromReimplementation =
getMcBasc(a.getColumnAsString(0),
a.getColumnAsString(1), metric);
System.out.println("From reimplementation" + fromReimplementation );
McBASCCovariance mcbascCovariane = new McBASCCovariance(a);
double fromPackage = mcbascCovariane.getScore(a, 0, 1);
System.out.println( "From package " + fromPackage );
assertEquals(fromPackage, fromReimplementation,0.01);
}
private static double getMcBasc(String s1, String s2, int [][] sMatrix) throws Exception
{
if( s1.length() != s2.length())
throw new Exception("No");
List<Double> listI = new ArrayList<Double>();
List<Double> listJ = new ArrayList<Double>();
for( int k=0; k < s1.length()-1; k++)
{
int iCharForK = MapResiduesToIndex.getIndex(s1.charAt(k));
int jCharForK = MapResiduesToIndex.getIndex(s2.charAt(k));
for(int l = k+1; l < s1.length(); l++ )
{
int iCharForL = MapResiduesToIndex.getIndex(s1.charAt(l));
int jCharForL = MapResiduesToIndex.getIndex(s2.charAt(l));
listI.add( (double) sMatrix[iCharForK][iCharForL]);
listJ.add( (double) sMatrix[jCharForK][jCharForL]);
}
}
return Pearson.getPearsonR(listI, listJ);
}
}
| 5,466 | 35.205298 | 118 | java |
cobs | cobs-master/cobs/test/FactorialsTest.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package test;
import java.math.BigDecimal;
import java.math.BigInteger;
import utils.Factorials;
import junit.framework.TestCase;
public class FactorialsTest extends TestCase
{
public FactorialsTest(String arg0)
{
super(arg0);
}
public void testBinomialSum() throws Exception
{
assertEquals( Factorials.getBinomialSum(75, 0, 0.5f), 1, 0.01);
BigDecimal bigD = Factorials.getBinomial( 75, 0, 0.5f);
for ( int x=1; x<=30; x++ )
{
bigD = bigD.add(Factorials.getBinomial( 75, x, 0.5f));
}
assertEquals( bigD.doubleValue(), 1.0 - Factorials.getBinomialSum(75, 31, 0.5f), 0.01);
}
public void testGetBinomial() throws Exception
{
BigDecimal aDistribution = Factorials.getBinomial(7,2,.583f);
assertEquals( aDistribution.doubleValue(), 0.09, 0.01);
}
public void testLnChoose() throws Exception
{
assertEquals( Math.log(Factorials.choose(7,2).doubleValue()),
Factorials.getLnChoose(7,2) , 0.001);
double lnTwoHundredFactorial = 859.6634733;
double lnOneHundredNinetyEightFactorial = 849.0768721;
double bottomLnchooseTwoHundredTwo = lnOneHundredNinetyEightFactorial + Math.log(2);
double lnchooseTwoHundredTwo = lnTwoHundredFactorial - bottomLnchooseTwoHundredTwo;
assertEquals(lnchooseTwoHundredTwo, Factorials.getLnChoose(200,2), 0.01);
assertEquals(lnchooseTwoHundredTwo, Factorials.getLnChoose(200,198), 0.01);
assertEquals( Factorials.getLnChoose(5000, 1000), Factorials.getLnChoose(5000, 4000), 0.01);
assertEquals( Factorials.getLnBinomial(120, 23, 0.5f),
Math.log(Factorials.getBinomial(120,23, 0.5f).doubleValue()), 0.01);
}
public void testFactorial() throws Exception
{
assertEquals( Factorials.getFactorial(5).intValue(), 120 );
assertEquals( Factorials.choose( 5, 2).intValue(), 10);
assertEquals( Factorials.choose( 6, 3).intValue(), 20 );
assertEquals( Factorials.choose( 3,0).intValue(), 1);
assertEquals( Factorials.choose( 0, 0).intValue(), 1);
assertEquals( Factorials.choose( 1, 1).intValue(), 1);
assertEquals( Factorials.choose( 30, 3).intValue(), Factorials.choose(30, 27).intValue() );
assertEquals( Factorials.getFactorial(0).intValue(), 1);
assertEquals( Factorials.getFactorial(1).intValue(), 1);
assertEquals( Factorials.getFactorial(2).intValue(), 2);
assertEquals( Factorials.getFactorial(3).intValue(), 6);
for ( int x= Factorials.NUM_TO_CALCULATE-1; x > 0; x-- )
{
BigInteger newVal = Factorials.getFactorial(x).divide( Factorials.getFactorial(x-1));
assertEquals( newVal.intValue(), x);
}
}
public void testBinomial() throws Exception
{
BigDecimal sum = new BigDecimal("0");
for ( int x=0; x<=150; x++)
sum = sum.add( Factorials.getBinomial(150, x, 0.5f));
assertEquals(sum.doubleValue(), 1.0, 0.01);
}
}
| 3,455 | 30.135135 | 94 | java |
cobs | cobs-master/cobs/test/TestNumberOfElements.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package test;
import java.util.HashMap;
import java.util.StringTokenizer;
import covariance.parsers.PfamToPDBBlastResults;
import junit.framework.TestCase;
public class TestNumberOfElements extends TestCase
{
public void test() throws Exception
{
HashMap<String, PfamToPDBBlastResults> map = PfamToPDBBlastResults.getAsMap();
for(PfamToPDBBlastResults pfamToPdb : map.values())
{
System.out.println(pfamToPdb.getOriginalLine());
String[] elements = pfamToPdb.getElements().split(",");
assertEquals(elements.length, pfamToPdb.getNumberOfElements());
int oldFirstElement =-1;
int oldSecondElement =-1;
for( String e : elements )
{
int firstElement = getFirstElement(e, pfamToPdb.getChainId());
int secondElement = getSecondElement(e,pfamToPdb.getChainId());
System.out.println(firstElement + " " + secondElement + " " + pfamToPdb.getPdbStart() + " " + pfamToPdb.getPdbEnd() );
assertTrue(secondElement >= firstElement);
assertTrue( firstElement >= pfamToPdb.getPdbStart() );
assertTrue( firstElement <= pfamToPdb.getPdbEnd());
assertTrue( secondElement >= pfamToPdb.getPdbStart() );
assertTrue( secondElement <= pfamToPdb.getPdbEnd());
assertTrue( firstElement > oldFirstElement );
assertTrue( firstElement >= oldSecondElement);
assertTrue( secondElement > oldFirstElement);
assertTrue( secondElement >= oldSecondElement);
oldFirstElement = firstElement;
oldSecondElement = secondElement;
}
}
}
static int getFirstElement(String s, char chainID)
{
StringTokenizer sToken = new StringTokenizer(s, "-");
return getPosition(sToken.nextToken(),chainID);
}
static int getSecondElement(String s, char chainID)
{
StringTokenizer sToken = new StringTokenizer(s, "-");
sToken.nextToken();
return getPosition(sToken.nextToken(),chainID);
}
static int getPosition( String s, char chainID)
{
StringBuffer buff = new StringBuffer();
for(Character c : s.toCharArray())
{
if( Character.isDigit(c))
buff.append(c);
}
if( Character.isDigit(chainID))
buff = new StringBuffer( buff.toString().substring(1) );
return Integer.parseInt(buff.toString());
}
}
| 2,847 | 30.644444 | 122 | java |
cobs | cobs-master/cobs/scripts/DownloadPDBFiles.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package scripts;
import java.util.HashMap;
import covariance.parsers.PfamToPDBBlastResults;
public class DownloadPDBFiles
{
public static void main(String[] args) throws Exception
{
HashMap<String, PfamToPDBBlastResults> pdbMap = PfamToPDBBlastResults.getAsMap();
int numDone=0;
for(PfamToPDBBlastResults pdb : pdbMap.values())
{
numDone++;
System.out.println( pdb.getPdbID() + " " + pdb.getPdbID() + " " + numDone + " " + pdbMap.values().size());
PdbDownloadFromHTTP.downloadIfNotThere(pdb.getPdbID());
}
}
}
| 1,183 | 29.358974 | 110 | java |
cobs | cobs-master/cobs/scripts/WriteTruncatedPfamAlignments.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package scripts;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import covariance.parsers.PfamToPDBBlastResults;
import utils.ConfigReader;
public class WriteTruncatedPfamAlignments
{
public static void main(String[] args) throws Exception
{
System.out.println(ConfigReader.getFullPfamPath());
boolean zipped = ConfigReader.getFullPfamPath().toLowerCase().endsWith("gz");
BufferedReader reader =
zipped ? new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( ConfigReader.getFullPfamPath()) ) ),100000)
: new BufferedReader( new FileReader( new File( ConfigReader.getFullPfamPath())),100000);
HashMap<String, PfamToPDBBlastResults> pdbMap= PfamToPDBBlastResults.getAsMap();
File outFile = new File("pfamTruncated.txt");
System.out.println(outFile.getAbsolutePath());
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
boolean writeLine = true;
for(String s = reader.readLine(); s != null; s= reader.readLine())
{
if(s.startsWith("#=GF ID"))
{
StringTokenizer sToken = new StringTokenizer(s);
sToken.nextToken(); sToken.nextToken();
String familyId = sToken.nextToken();
if( pdbMap.containsKey(familyId))
{
System.out.println("Writing " + familyId);
writeLine =true;
}
else
{
System.out.println("Not Writing " + familyId);
writeLine =false;
}
}
if( writeLine)
writer.write(s + "\n");
writer.flush();
}
writer.flush(); writer.close();
reader.close();
}
}
| 2,459 | 27.604651 | 94 | java |
cobs | cobs-master/cobs/scripts/PdbDownloadFromHTTP.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package scripts;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import utils.ConfigReader;
public class PdbDownloadFromHTTP
{
public static void main(String[] args) throws Exception
{
BufferedReader reader = new BufferedReader(new FileReader(new File(ConfigReader.getPdbPfamChain() )));
reader.readLine();
for(String s = reader.readLine(); s != null; s = reader.readLine())
{
String pdbID = s.split("\t")[3];
downloadIfNotThere(pdbID);
}
reader.close();
}
public static void downloadIfNotThere(String fourChar) throws Exception
{
File pdbFile = new File(ConfigReader.getPdbDir() + File.separator +
fourChar + ".txt");
if(pdbFile.exists())
{
System.out.println(pdbFile.getAbsolutePath() + " exists!");
return;
}
URL url = new URL( "http://www.rcsb.org/pdb/files/" + fourChar + ".pdb.gz");
System.out.println(url.toString());
BufferedReader reader =
new BufferedReader(new InputStreamReader(
new GZIPInputStream( url.openStream())));
BufferedWriter writer = new BufferedWriter(new FileWriter(pdbFile));
for(String s = reader.readLine(); s != null; s = reader.readLine())
{
writer.write(s + "\n");
}
reader.close();
writer.flush(); writer.close();
System.out.println("Got" + fourChar);
}
}
| 2,133 | 26.012658 | 104 | java |
cobs | cobs-master/cobs/covariance/algorithms/ELSCCovarianceSubAlignment.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.io.*;
import java.math.*;
import java.util.*;
import utils.Factorials;
import utils.MapResiduesToIndex;
import covariance.datacontainers.Alignment;
/** Todo: This and LocklessCoVariance could probably both become members of a Covariance subclass.
* ( Probably not really worth doing, though....)
*/
public class ELSCCovarianceSubAlignment
{
private double[] dekkerCovarianceScores = null;
private Alignment fullAlignment;
private Alignment subsetAlignment;
private static final BigInteger ONE = new BigInteger("1");
public Alignment getFullAlignment()
{
return this.fullAlignment;
}
public Alignment getSubsetAlignment()
{
return this.subsetAlignment;
}
public List getSubsetAlignmentLines()
{
return subsetAlignment.getAlignmentLines();
}
public ELSCCovarianceSubAlignment(Alignment a,
int filterResidueNum,
char filterResidueChar) throws Exception
{
if ( filterResidueChar != '-' )
{
this.fullAlignment = a;
this.subsetAlignment = JavaSCA.getSubsetAlignment( a, filterResidueNum, filterResidueChar );
//System.out.println("Full = " + this.fullAlignment.getAlignmentLines().size() );
//System.out.println("Subset = " + this.subsetAlignment.getAlignmentLines().size() );
}
}
private int getSumAcrossResidues( int[][] counts, int position )
{
int sum = 0;
for ( int x=0; x< MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
sum+=counts[position][x];
return sum;
}
/** The sum of locklessIdealizedCounts should equal the total number of valid residues in that column
* ( passed in as N )
*/
public static void adjustCounts( int[][] idealizedCounts, int N, LinkedList remainderList, int residuePosition )
throws Exception
{
long numIdealized = 0;
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
numIdealized+= idealizedCounts[residuePosition][y];
if ( numIdealized == N )
return;
Collections.sort( remainderList );
while ( numIdealized < N )
{
RemainderClass rClass = (RemainderClass) remainderList.removeLast();
idealizedCounts[residuePosition][ rClass.getOriginalIndex()]++;
numIdealized++;
}
// just a sanity check
long check = 0;
for ( int x=0; x< MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
check+= idealizedCounts[residuePosition][x];
if ( check != N )
throw new Exception("Logic Error!");
}
private int[][] getIdealizedCounts(int[][] subsetCounts, int[][] fullCounts ) throws Exception
{
int[][] idealizedCounts = new int[ subsetCounts.length][MapResiduesToIndex.NUM_VALID_RESIDUES];
for ( int x=0; x<subsetCounts.length; x++ )
{
LinkedList remainderList = new LinkedList();
int n = getSumAcrossResidues( subsetCounts, x );
int N = getSumAcrossResidues( fullCounts, x );
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
{
float idealCount = 0;
if ( N > 0 )
idealCount = ((float) n) * fullCounts[x][y] / N;
idealizedCounts[x][y] = ( int ) idealCount;
float remainder = idealCount - idealizedCounts[x][y];
remainderList.add( new RemainderClass( remainder,y));
}
adjustCounts( idealizedCounts, n, remainderList, x);
}
return idealizedCounts;
}
public void dumpAllData( BufferedWriter writer ) throws Exception
{
double[] covarianceScores = getCovarianceScores();// initialize
int[][] fullCounts = fullAlignment.getCounts();
int[][] subsetCounts = subsetAlignment.getCounts();
int[][] idealizedCounts = getIdealizedCounts( subsetCounts, fullCounts );
writer.write("position\tresidue\tfullCounts\tsubsetCounts\tidealizedCounts\tcovarianceScores\n");
for ( int x=0; x< fullAlignment.getNumColumnsInAlignment(); x++ )
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
{
writer.write( x + "\t" );
writer.write( MapResiduesToIndex.getChar(y) + "\t" );
writer.write( fullCounts[x][y] + "\t" );
writer.write( subsetCounts[x][y] + "\t" );
writer.write( idealizedCounts[x][y] + "\t" );
writer.write( covarianceScores[x] + "\n" );
}
writer.flush();
}
public synchronized double[] getCovarianceScores() throws Exception
{
if ( dekkerCovarianceScores == null )
{
this.dekkerCovarianceScores = new double[fullAlignment.getNumColumnsInAlignment()];
int[][] fullCounts = fullAlignment.getCounts();
int[][] subsetCounts = subsetAlignment.getCounts();
int[][] idealizedCounts = getIdealizedCounts( subsetCounts, fullCounts );
for ( int x=0; x < fullAlignment.getNumColumnsInAlignment(); x++ )
{
double top = 0;
double bottom = 0;
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
{
top += Factorials.getLnChoose( (int) fullCounts[x][y], (int) subsetCounts[x][y] );
if ( fullCounts[x][y] > idealizedCounts[x][y] )
bottom += Factorials.getLnChoose( (int) fullCounts[x][y], (int)idealizedCounts[x][y]);
}
dekkerCovarianceScores[x] = - ( top - bottom);
}
}
return dekkerCovarianceScores;
}
}
| 5,763 | 29.020833 | 113 | java |
cobs | cobs-master/cobs/covariance/algorithms/MICovariance.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Iterator;
import utils.MapResiduesToIndex;
import covariance.datacontainers.Alignment;
public class MICovariance implements ScoreGenerator
{
private Alignment a;
private ConservationSum cSum;
public MICovariance(Alignment a) throws Exception
{
this.a = a;
this.cSum = new ConservationSum(a);
}
@Override
public Alignment getAlignment()
{
return a;
}
public String getAnalysisName()
{
return "MI";
}
// public for testing
public static class PairsClass
{
public String pair;
public int num;
PairsClass( String pair )
{
this.pair = pair;
num = 0;
}
void increment()
{
num++;
}
}
/** The key is the two char string representing that pair
* The values is a PairsClass object
*/
public HashMap getPairs( String iString,
String jString,
int[] iFreqs,
int[] jFreqs) throws Exception
{
HashMap pairs = new HashMap();
for ( int i=0; i< iFreqs.length; i++ )
for ( int j=0; j < jFreqs.length; j++ )
if ( iFreqs[i] > 0 && jFreqs[j] > 0 )
{
String pair = "" + MapResiduesToIndex.getChar( i ) + MapResiduesToIndex.getChar( j );
pairs.put( pair, new PairsClass( pair ));
}
for ( int x=0; x< iString.length(); x++ )
{
char iChar = iString.charAt(x);
char jChar = jString.charAt(x);
String pair = "" + iChar+ jChar;
((PairsClass) pairs.get( pair )).increment();
}
return pairs;
}
public static int[] getFrequencies(String string) throws Exception
{
int[] frequencies = new int[ MapResiduesToIndex.NUM_VALID_RESIDUES ];
for ( int x=0; x< string.length(); x++ )
{
frequencies[ MapResiduesToIndex.getIndex( string.charAt(x) )]++;
}
return frequencies;
}
public double getCovarianceScore( HashMap pairs,
int numValidSequences,
int[] iFrequencies,
int[] jFrequencies) throws Exception
{
if ( numValidSequences <= 0 )
return 0;
double covarianceScore = 0;
for ( Iterator it = pairs.values().iterator();
it.hasNext(); )
{
PairsClass pClass= (PairsClass) it.next();
char iChar = pClass.pair.charAt(0);
char jChar = pClass.pair.charAt(1);
// the frequency of residue x at position i
float fxi = ((float)iFrequencies[ MapResiduesToIndex.getIndex(iChar)]) / numValidSequences;
//System.out.println( "Freq of " + MapResiduesToIndex.getChar( cvh.getIResidue()) + "=" + fxi );
// the frequency of residue y at poistion j
float fyj = ((float) jFrequencies[ MapResiduesToIndex.getIndex(jChar)] ) / numValidSequences;
// frequency of sequences that cotain an x at pos i and a y at position j
float jointProb = ((float)pClass.num) / numValidSequences;
if ( pClass.num > 0 )
{
//System.out.println( fxi + " " + fyj + " " + jointProb );
covarianceScore += (float) (jointProb * Math.log(jointProb / ( fxi * fyj )));
}
}
return covarianceScore;
}
public Double getScore(Alignment alignment, int i, int j) throws Exception
{
if ( a != alignment )
throw new Exception("Please call on same alignment that was passed in to constructor");
String iString = alignment.getColumnAsString(i);
String jString= alignment.getColumnAsString(j);
if ( iString.length() != jString.length() )
throw new Exception("Logic error");
StringBuffer iStringNew = new StringBuffer();
StringBuffer jStringNew= new StringBuffer();
for ( int x=0; x< iString.length(); x++ )
{
char iListChar = iString.charAt(x);;
char jListChar = jString.charAt(x);
if ( MapResiduesToIndex.isValidResidueChar( iListChar ) &&
MapResiduesToIndex.isValidResidueChar( jListChar ) )
{
iStringNew.append( iListChar );
jStringNew.append( jListChar );
}
}
iString = iStringNew.toString();
jString = jStringNew.toString();
int[] iFrequencies = getFrequencies( iString );
int[] jFrequencies = getFrequencies( jString);
HashMap pairs = getPairs( iString, jString, iFrequencies, jFrequencies );
double score = getCovarianceScore( pairs, iString.length(), iFrequencies, jFrequencies );
double cScore = Math.max( cSum.getScore(i), cSum.getScore(j));
// perfectly conserved columns do not covary, so this is ok to do
if ( cScore == 0 )
return 0.0;
return score;
//return score / cScore;
}
public static void main(String[] args) throws Exception
{
if ( args.length != 2 )
{
System.out.println( "Usage MICovariance inAlignment outFile" );
return;
}
Alignment a = new Alignment("1", new File( args[0]), false );
MICovariance mi = new MICovariance(a);
BufferedWriter writer = new BufferedWriter( new FileWriter( new File(
args[1] )));
writer.write( "i\tj\tscore\n");
for ( int i =0; i < a.getNumColumnsInAlignment(); i++ )
if ( a.columnHasValidResidue(i) )
for ( int j = i + 1; j < a.getNumColumnsInAlignment(); j++ )
if ( a.columnHasValidResidue(j) )
writer.write( i + "\t" + j + "\t" + mi.getScore(a, i, j) + "\n" );
writer.flush(); writer.close();
}
public boolean isSymmetrical()
{
return true;
}
public boolean reverseSort()
{
return false;
}
}
| 5,998 | 25.311404 | 99 | java |
cobs | cobs-master/cobs/covariance/algorithms/RemainderClass.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
public class RemainderClass implements Comparable
{
private int orginalIndex;
private float remainder;
public int getOriginalIndex()
{
return this.orginalIndex;
}
public float getRemainder()
{
return this.remainder;
}
public RemainderClass( float remainder, int orginalIndex )
{
this.remainder = remainder;
this.orginalIndex = orginalIndex;
}
/** Sorts in ascending order
*/
public int compareTo(Object o)
{
return Float.compare( this.remainder, ((RemainderClass)o).remainder );
}
public String toString()
{
return orginalIndex + " " + remainder;
}
}
| 1,271 | 23.941176 | 74 | java |
cobs | cobs-master/cobs/covariance/algorithms/JavaSCA.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.util.*;
import utils.*;
import covariance.datacontainers.*;
public class JavaSCA implements ScoreGenerator
{
private Alignment alignment;
private double[][] locklessScores;
private JavaSCA lastSubLockless;
private int lastI = -99;
char[] mostFrequentresidues;
// from the Ranganathan lab
public static float background[] =
{0.072658f, 0.024692f, 0.050007f, 0.061087f,
0.041774f, 0.071589f, 0.023392f, 0.052691f, 0.063923f,
0.089093f, 0.023150f, 0.042931f, 0.052228f, 0.039871f,
0.052012f, 0.073087f, 0.055606f, 0.063321f, 0.012720f,
0.032955f};
@Override
public Alignment getAlignment()
{
return alignment;
}
public JavaSCA( Alignment alignment ) throws Exception
{
this.alignment = alignment;
initializeLocklessScores();
mostFrequentresidues= Alignment.getMostFrequentResidues(alignment);
}
public double[][] getLocklessScores()
{
return this.locklessScores;
}
public double getLocklessSum(int i)
{
double sum = 0;
for ( int x=0; x< MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
{
double temp = locklessScores[i][x];
sum += temp * temp;
}
return Math.sqrt( sum );
}
private JavaSCA( Alignment fullAlignment, char[] residues, int i ) throws Exception
{
if ( residues[i] != '-' )
{
this.alignment = getSubsetAlignment( fullAlignment, i, residues[i] );
initializeLocklessScores();
}
}
public static Alignment getSubsetAlignment( Alignment fullAlignment,
int filterResidueNumber,
char filterResidueChar )
throws Exception
{
if ( ! MapResiduesToIndex.isValidResidueChar( filterResidueChar ) )
throw new Exception("Error! " + filterResidueChar + " is not a vaild amino acid residue");
if ( filterResidueNumber < 0 )
throw new Exception("Error! Filter residue number must be positive!");
if ( filterResidueNumber > fullAlignment.getNumColumnsInAlignment() )
throw new Exception("Error! Filter residue number is longer than the sequence alignment");
List subsetAlignmentLines = new ArrayList();
for ( Iterator i = fullAlignment.getAlignmentLines().iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
if ( aLine.getSequence().charAt( filterResidueNumber ) == filterResidueChar )
subsetAlignmentLines.add( aLine );
}
return new Alignment( filterResidueNumber + "_" + filterResidueChar + fullAlignment.getAligmentID(),
subsetAlignmentLines) ;
}
private static double getLnProbability(int aaIndex,
int N,
double nx) throws Exception
{
double returnVal = TTest.lnfactorial(N);
returnVal -= TTest.lnfactorial(nx);
returnVal -= TTest.lnfactorial(N-nx);
returnVal += nx * Math.log(background[aaIndex]);
returnVal += (N-nx) * Math.log(1.0-background[aaIndex]);
return returnVal;
}
private void initializeLocklessScores() throws Exception
{
int[][] counts = this.alignment.getCounts(); // initialize count array
float[] frequencies = this.alignment.getFrequencies(); // initialize frequency array
this.locklessScores = new double[ counts.length][MapResiduesToIndex.NUM_VALID_RESIDUES];
for ( int x=0; x < counts.length; x++ )
{
for ( int y=0; y< MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
{
this.locklessScores[x][y] = getLnProbability( y, 100, (((double)100*counts[x][y])/
this.alignment.getNumSequencesInAlignment()));
}
}
}
/** This will work a lot faster if you call all the j's for the same i since the last
* called subalignment i is cached
*/
public Double getScore( Alignment alignment, int i, int j ) throws Exception
{
if ( mostFrequentresidues[i] == '-' )
throw new Exception("Error! No valid residues at position " + i );
if ( this.alignment != alignment )
throw new Exception( "Error! Call with same alignment passed in from constructor");
if ( lastSubLockless == null || lastI != i )
{
this.lastSubLockless = new JavaSCA( alignment, mostFrequentresidues, i );
lastI = i;
}
double score = 0;
for ( int x=0; x< MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
{
double temp = lastSubLockless.locklessScores[j][x] - this.locklessScores[j][x];
score += temp * temp;
}
double returnVal = Math.sqrt( score );
return returnVal;
}
public static void main(String[] args) throws Exception
{
System.out.println(Factorials.getBinomial(12, 7, 0.012720f));
}
/*
public static void main(String[] args) throws Exception
{
if ( args.length != 2 )
{
System.out.println( "Usage JavaSCA inAlignment outFile" );
return;
}
Alignment a = new Alignment("1", new File( args[0]), false );
JavaSCA sca = new JavaSCA(a);
BufferedWriter writer = new BufferedWriter( new FileWriter( new File(
args[1] )));
writer.write( "i\tj\tscore\n");
for ( int i =0; i < a.getNumColumnsInAlignment(); i++ )
if ( a.columnHasValidResidue(i) )
for ( int j = i + 1; j < a.getNumColumnsInAlignment(); j++ )
if ( a.columnHasValidResidue(j) )
writer.write( i + "\t" + j + "\t" + sca.getScore(a, i, j) + "\n" );
writer.flush(); writer.close();
}
*/
public boolean isSymmetrical()
{
return false;
}
public boolean reverseSort()
{
return false;
}
public String getAnalysisName()
{
return "JavaSCA";
}
}
| 6,124 | 26.222222 | 102 | java |
cobs | cobs-master/cobs/covariance/algorithms/McBASCCovariance.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
import utils.MapResiduesToIndex;
import covariance.datacontainers.Alignment;
import covariance.datacontainers.AlignmentLine;
public class McBASCCovariance implements ScoreGenerator
{
private HashMap<String, Double> cachedVals = new HashMap<String,Double>();
public static final String MCBASC_ANALYSIS = "McBASC";
private static volatile int[][] maxhomMetric;
private static Object maxhomMetricGuard = new Object();
private float[] averages;
private float[] sds;
private Alignment a;
private int numSquared;
@Override
public Alignment getAlignment()
{
return a;
}
private void initialize() throws Exception
{
getMaxhomMetric(); // initalize array
this.numSquared = a.getNumSequencesInAlignment() * a.getNumSequencesInAlignment();
averages = new float[a.getNumColumnsInAlignment()];
sds = new float[a.getNumColumnsInAlignment()];
for ( int i=0; i < a.getNumColumnsInAlignment(); i++ )
{
long sum = 0;
long sumSquared = 0;
int numComparisons = 0;
for ( int x=0; x < a.getNumSequencesInAlignment(); x++ )
{
String lineX = ((AlignmentLine) a.getAlignmentLines().get(x)).getSequence();
char xi = lineX.charAt(i);
// could make the algorithm 2X faster by having this loop be
// "for ( int y=x+1; y < a.getNumSequencesInAlignment(); y++ ) "
for ( int y=0; y < a.getNumSequencesInAlignment(); y++ )
{
// should probably uncomment this so columns are not compared to themselves
// but, for better or worse, that's not the way we described the algorithm in the paper...
//if ( y != x )
{
String lineY = ((AlignmentLine) a.getAlignmentLines().get(y)).getSequence();;
char yi = lineY.charAt(i);
if ( MapResiduesToIndex.isValidResidueChar(xi) &&
MapResiduesToIndex.isValidResidueChar(yi) )
{
numComparisons++;
int metric =
maxhomMetric[ MapResiduesToIndex.getIndex(xi) ][MapResiduesToIndex.getIndex(yi)];
sum+= metric;
sumSquared += metric * metric;
}
}
}
}
if ( numComparisons == 0 )
{
averages[i] =0;
sds[i] = 0;
}
else if ( numComparisons == 1 )
{
averages[i] = sum;
sds[i] = 0;
}
else
{
averages[i]= ((float) sum) / numComparisons;
float top = sumSquared;
top -= ((float)sum) * sum / numComparisons;
top /= ((float)numComparisons) - 1;
if ( Math.abs(top) < 0.0000000001 )
sds[i] = 0;
else
sds[i] = (float) Math.sqrt(top);
if ( Float.isNaN(sds[i])|| Float.isInfinite(sds[i]) )
sds[i] = 0;
}
}
}
public McBASCCovariance( Alignment a) throws Exception
{
this.a = a;
initialize();
}
public static int[][] getMaxhomMetric() throws Exception
{
synchronized ( maxhomMetricGuard)
{
if ( maxhomMetric == null )
{
maxhomMetric = new int[MapResiduesToIndex.NUM_VALID_RESIDUES][MapResiduesToIndex.NUM_VALID_RESIDUES];
for ( int x=0; x< MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++)
maxhomMetric[x][y] = -99;
fillMatrixFromFile(maxhomMetric);
for ( int x=0; x< MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++)
if ( maxhomMetric[x][y] == -99 )
throw new Exception("Unfilled positon " + x + " " + y );
}
}
return maxhomMetric;
}
private static void fillMatrixFromFile(int[][] matrix) throws Exception
{
String runningDirectory = McBASCCovariance.class.getProtectionDomain().getCodeSource().getLocation().getPath();
BufferedReader reader = new BufferedReader( new FileReader( new File(
runningDirectory + File.separator + "data" + File.separator +
"Maxhom_McLachlan.metric" )));
String firstLine = reader.readLine();
StringTokenizer sToken = new StringTokenizer( firstLine );
char[] topRow = new char[MapResiduesToIndex.NUM_VALID_RESIDUES];
for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
{
String nextChar = sToken.nextToken();
if ( nextChar.length() != 1 )
throw new Exception("Unexpected token " + nextChar );
topRow[x] = nextChar.charAt(0);
}
for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
{
StringTokenizer lineTokens = new StringTokenizer( reader.readLine() );
String nextChar = lineTokens.nextToken();
if ( nextChar.length() != 1 )
throw new Exception("Unexpected token " + nextChar );
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
{
matrix[ MapResiduesToIndex.getIndex( nextChar.charAt(0))][ MapResiduesToIndex.getIndex( topRow[y])] =
(int) Float.parseFloat(lineTokens.nextToken());
}
}
}
public String getAnalysisName()
{
return MCBASC_ANALYSIS;
}
public static void main(String[] args) throws Exception
{
if ( args.length != 2 )
{
System.out.println( "Usage McBASCCovariance inAlignment outFile" );
return;
}
Alignment a = new Alignment("1", new File( args[0]), true );
a = a.getFilteredAlignment(90);
McBASCCovariance mcBasc = new McBASCCovariance(a);
BufferedWriter writer = new BufferedWriter( new FileWriter( new File(
args[1] )));
writer.write( "i\tj\tscore\n");
for ( int i =0; i < a.getNumColumnsInAlignment(); i++ )
if ( a.columnHasValidResidue(i) )
for ( int j = i + 1; j < a.getNumColumnsInAlignment(); j++ )
if ( a.columnHasValidResidue(j) )
writer.write( i + "\t" + j + "\t" + mcBasc.getScore(a, i, j) + "\n" );
writer.flush(); writer.close();
}
public float getMatrixTopScore( int i, int j, char xi, char xj, char yi, char yj )
throws Exception
{
if ( MapResiduesToIndex.isValidResidueChar(xi) &&
MapResiduesToIndex.isValidResidueChar(yi) &&
MapResiduesToIndex.isValidResidueChar(xj) &&
MapResiduesToIndex.isValidResidueChar(yj) )
{
int iScore = maxhomMetric[MapResiduesToIndex.getIndex(xi)][MapResiduesToIndex.getIndex(yi)];
int jScore = maxhomMetric[MapResiduesToIndex.getIndex(xj)][MapResiduesToIndex.getIndex(yj)];
float top = (iScore- averages[i]);
top *= (jScore - averages[j]);
//System.out.println( i + " " + j + " " + xi + " " + xj + " " + yi + " " + yj + " " + top );
return top;
}
return 0;
}
/*
This method makes somes approximations for performance which don't really have to be made.
These approximations effect alignments with few sequences in them ( see comments below).
A cleaner version could return exact values in less time.
But McBASC was working pretty well in our paper (in which we only used alignments with >50 sequences
so the approximations we used were nearly exact), so I basically didn't want to mess with it.
As always, your milage may vary. If you are using smaller alignments, you can fix these approximations
as indicated in the comments in this method.
*/
public synchronized Double getScore(Alignment a, int i, int j) throws Exception
{
if ( a != this.a )
throw new Exception("Please call on alignment passed into constructor!");
// if either column is perfectly conserved, move it somewhere out of the way
if ( sds[i] == 0 || sds[j] == 0 )
return COBS_CONSISTENT;
String key = i +"@" + j;
if( cachedVals.containsKey(key) )
return cachedVals.get(key);
float sum = 0;
for ( int x=0; x < a.getNumSequencesInAlignment(); x++ )
{
String lineX = ((AlignmentLine) a.getAlignmentLines().get(x)).getSequence();
char xi = lineX.charAt(i);
char xj = lineX.charAt(j);
// a small bug here. When calculating the means and standard deviations in
// the constructor, we allowed each residue to be compared to itself
// here, when calcuating the final (i,j) score, we don't compare residues to themselves
// for any alignment with more than a non-trivial number of sequences ( > ~5-10), this bug
// makes essentially no difference
for ( int y=x + 1; y < a.getNumSequencesInAlignment(); y++ )
{
String lineY = ((AlignmentLine) a.getAlignmentLines().get(y)).getSequence();
char yi = lineY.charAt(i);
char yj = lineY.charAt(j);
sum += getMatrixTopScore(i, j, xi, xj, yi, yj);
}
}
double val = 2 * sum / ( this.numSquared * sds[i] * sds[j]);
cachedVals.put(key,val);
// the factor of 2 multiplication is an approximation for performance.
// the half triangle in the matrix does not have exactly half the comparisons of the
// full triangle. This approximation will approach being exact
// as the number of sequences in the alignment increases.
// For small alignments with few sequences, however, this approximation may effect the score
// Looking at this now, it seems kind of sloppy, but because we only used large aligments in the paper
// ( >50 sequences), it made almost no difference to our results
return val;
}
public boolean isSymmetrical()
{
return true;
}
public boolean reverseSort()
{
return false;
}
/** getters for testing
*/
public float[] getAverages()
{
return averages;
}
public float[] getSds()
{
return sds;
}
public int getNumSquared()
{
return numSquared;
}
}
| 10,200 | 29.27003 | 113 | java |
cobs | cobs-master/cobs/covariance/algorithms/ConservationGenerator.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
public interface ConservationGenerator
{
public double getScore( int i ) throws Exception;
}
| 767 | 35.571429 | 74 | java |
cobs | cobs-master/cobs/covariance/algorithms/OmesCovariance.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.io.*;
import java.util.*;
import utils.*;
import covariance.datacontainers.*;
public class OmesCovariance implements ScoreGenerator
{
private String idString;
private boolean tossSuspiciousPoints = false;
private Alignment a;
public OmesCovariance( Alignment a, String idString )
{
this.idString = idString;
this.a = a;
}
@Override
public Alignment getAlignment()
{
return a;
}
public static void main(String[] args) throws Exception
{
if ( args.length != 2 )
{
System.out.println( "Usage OmesCovariance inAlignment outFile" );
return;
}
Alignment a = new Alignment("1", new File( args[0]), true );
OmesCovariance omes = new OmesCovariance(a);
BufferedWriter writer = new BufferedWriter( new FileWriter( new File(
args[1] )));
writer.write( "i\tj\tscore\n");
for ( int i =0; i < a.getNumColumnsInAlignment(); i++ )
if ( a.columnHasValidResidue(i) )
for ( int j = i + 1; j < a.getNumColumnsInAlignment(); j++ )
if ( a.columnHasValidResidue(j) )
writer.write( i + "\t" + j + "\t" + omes.getScore(a, i, j) + "\n" );
writer.flush(); writer.close();
}
public OmesCovariance(Alignment a)
{
this(a, "OMES");
}
private static class PairsClass
{
String pair;
int num;
PairsClass( String pair )
{
this.pair = pair;
num = 0;
}
void increment()
{
num++;
}
}
private static Random random = new Random();
public String getAnalysisName()
{
return idString;
}
/** The key is the two char string representing that pair
* The values is a PairsClass object
*/
public HashMap getPairs( String iString,
String jString,
int[] iFreqs,
int[] jFreqs) throws Exception
{
HashMap pairs = new HashMap();
for ( int i=0; i< iFreqs.length; i++ )
for ( int j=0; j < jFreqs.length; j++ )
if ( iFreqs[i] > 0 && jFreqs[j] > 0 )
{
String pair = "" + MapResiduesToIndex.getChar( i ) + MapResiduesToIndex.getChar( j );
pairs.put( pair, new PairsClass( pair ));
}
for ( int x=0; x< iString.length(); x++ )
{
char iChar = iString.charAt(x);
char jChar = jString.charAt(x);
String pair = "" + iChar+ jChar;
((PairsClass) pairs.get( pair )).increment();
}
return pairs;
}
public static int[] getFrequencies(String string) throws Exception
{
int[] frequencies = new int[ MapResiduesToIndex.NUM_VALID_RESIDUES ];
for ( int x=0; x< string.length(); x++ )
{
frequencies[ MapResiduesToIndex.getIndex( string.charAt(x) )]++;
}
return frequencies;
}
public double getCovarianceScore( HashMap pairs,
int numValidSequences,
int[] iFrequencies,
int[] jFrequencies,
int i,
int j) throws Exception
{
if ( numValidSequences <= 0 )
return 0;
double covarianceScore = 0;
for ( Iterator it = pairs.values().iterator();
it.hasNext(); )
{
PairsClass pClass= (PairsClass) it.next();
char iChar = pClass.pair.charAt(0);
char jChar = pClass.pair.charAt(1);
// the frequency of residue x at position i
float fxi = ((float)iFrequencies[ MapResiduesToIndex.getIndex(iChar)]) / numValidSequences;
//System.out.println( "Freq of " + MapResiduesToIndex.getChar( cvh.getIResidue()) + "=" + fxi );
// the frequency of residue y at poistion j
float fyj = ((float) jFrequencies[ MapResiduesToIndex.getIndex(jChar)] ) / numValidSequences;
// expected number of sequences that cotain an x at pos i and a y at position j
float nex = numValidSequences * fxi * fyj;
float score = pClass.num - nex;
covarianceScore += score * score;
//System.out.println( iChar + "\t" + jChar + "\t" + pClass.num + "\t" + nex + "\t" + score*score );
}
return covarianceScore / numValidSequences;
}
public List getSubScores( Alignment alignment, int i, int j ) throws Exception
{
if ( alignment != this.a )
throw new Exception("Please call on the same alignment used in the constructor");
String iString = alignment.getColumnAsString(i);
String jString= alignment.getColumnAsString(j);
if ( iString.length() != jString.length() )
throw new Exception("Logic error");
StringBuffer iStringNew = new StringBuffer();
StringBuffer jStringNew= new StringBuffer();
for ( int x=0; x< iString.length(); x++ )
{
char iListChar = iString.charAt(x);;
char jListChar = jString.charAt(x);
if ( MapResiduesToIndex.isValidResidueChar( iListChar ) &&
MapResiduesToIndex.isValidResidueChar( jListChar ) )
{
iStringNew.append( iListChar );
jStringNew.append( jListChar );
}
}
iString = iStringNew.toString();
jString = jStringNew.toString();
int[] iFrequencies = getFrequencies( iString );
int[] jFrequencies = getFrequencies( jString);
HashMap pairs = getPairs( iString, jString, iFrequencies, jFrequencies );
int numValidSequences = iString.length();
List list = new ArrayList();
for ( Iterator it = pairs.values().iterator();
it.hasNext(); )
{
PairsClass pClass= (PairsClass) it.next();
char iChar = pClass.pair.charAt(0);
char jChar = pClass.pair.charAt(1);
// the frequency of residue x at position i
float fxi = ((float)iFrequencies[ MapResiduesToIndex.getIndex(iChar)]) / numValidSequences;
//System.out.println( "Freq of " + MapResiduesToIndex.getChar( cvh.getIResidue()) + "=" + fxi );
// the frequency of residue y at poistion j
float fyj = ((float) jFrequencies[ MapResiduesToIndex.getIndex(jChar)] ) / numValidSequences;
// expected number of sequences that cotain an x at pos i and a y at position j
float nex = numValidSequences * fxi * fyj;
float score = pClass.num - nex;
list.add( new AlignmentSubScore(iChar, jChar, pClass.num, nex, score * score ));
}
return list;
}
public Double getScore( Alignment alignment, int i, int j ) throws Exception
{
if ( alignment != this.a )
throw new Exception("Please call on the same alignment used in the constructor");
String iString = alignment.getColumnAsString(i);
String jString= alignment.getColumnAsString(j);
if ( iString.length() != jString.length() )
throw new Exception("Logic error");
StringBuffer iStringNew = new StringBuffer();
StringBuffer jStringNew= new StringBuffer();
for ( int x=0; x< iString.length(); x++ )
{
char iListChar = iString.charAt(x);;
char jListChar = jString.charAt(x);
if ( MapResiduesToIndex.isValidResidueChar( iListChar ) &&
MapResiduesToIndex.isValidResidueChar( jListChar ) )
{
iStringNew.append( iListChar );
jStringNew.append( jListChar );
}
}
iString = iStringNew.toString();
jString = jStringNew.toString();
int[] iFrequencies = getFrequencies( iString );
int[] jFrequencies = getFrequencies( jString);
HashMap pairs = getPairs( iString, jString, iFrequencies, jFrequencies );
return getCovarianceScore( pairs, iString.length(), iFrequencies, jFrequencies, i, j );
}
public boolean isSymmetrical()
{
return true;
}
public boolean reverseSort()
{
return false;
}
public void setTossSuspiciousPoints(boolean tossSuspiciousPoints)
{
this.tossSuspiciousPoints = tossSuspiciousPoints;
}
public boolean isTossSuspiciousPoints()
{
return tossSuspiciousPoints;
}
}
| 8,070 | 26.083893 | 102 | java |
cobs | cobs-master/cobs/covariance/algorithms/ConservationSum.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.io.*;
import utils.*;
import covariance.datacontainers.*;
public class ConservationSum implements ScoreGenerator, ConservationGenerator
{
private double[] absoluteSequenceEntropy;
private Alignment alignment;
private String id;
@Override
public Alignment getAlignment()
{
return alignment;
}
public Double getScore( Alignment a, int i, int j ) throws Exception
{
if ( a != this.alignment )
throw new Exception("Please call getScore() with the same alignment used in the constructor");
return (absoluteSequenceEntropy[i] + absoluteSequenceEntropy[j]) / 2;
}
public static void main(String[] args) throws Exception
{
if ( args.length != 2 )
{
System.out.println( "Usage ConservationSum inAlignment outFile" );
return;
}
Alignment a = new Alignment("1", new File( args[0]), false );
ConservationSum cSum = new ConservationSum(a);
BufferedWriter writer = new BufferedWriter( new FileWriter( new File(
args[1] )));
writer.write( "i\tj\tscore\n");
for ( int i =0; i < a.getNumColumnsInAlignment(); i++ )
if ( a.columnHasValidResidue(i) )
for ( int j = i + 1; j < a.getNumColumnsInAlignment(); j++ )
if ( a.columnHasValidResidue(j) )
writer.write( i + "\t" + j + "\t" + cSum.getScore(a, i, j) + "\n" );
writer.flush(); writer.close();
}
public double getScore( int i ) throws Exception
{
return absoluteSequenceEntropy[i];
}
public ConservationSum(Alignment a, String id) throws Exception
{
this.id = id;
this.alignment = a;
int[][] counts = a.getCounts();
absoluteSequenceEntropy = new double[ a.getNumColumnsInAlignment()];
for ( int x=0; x < a.getNumColumnsInAlignment(); x++ )
{
absoluteSequenceEntropy[x] = 0.0;
long total = 0;
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
total += counts[x][y];
for ( int y=0; y< MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
{
float frequency = ((float) counts[x][y]) / total;
if ( frequency > 0.0 )
absoluteSequenceEntropy[x] += ( frequency * Math.log( frequency));
}
absoluteSequenceEntropy[x] = - absoluteSequenceEntropy[x];
}
}
public String getAnalysisName()
{
return id;
}
public boolean isSymmetrical()
{
return true;
}
public boolean reverseSort()
{
return true;
}
public ConservationSum(Alignment a) throws Exception
{
this( a, "ConservationSum");
}
}
| 3,132 | 24.471545 | 97 | java |
cobs | cobs-master/cobs/covariance/algorithms/ScoreGenerator.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import covariance.datacontainers.*;
public interface ScoreGenerator
{
//Original 2004 paper method of excluding McBasc perfect conservation columns
public static final double NO_SCORE = -2;
//Because of the way that Pearson's is calculated for COBS (using a "TINY" double value)
//McBasc will now need to score a 0 so that we are making the same assumptions in the code base.
public static final double COBS_CONSISTENT = 1.0;
public Double getScore( Alignment a, int i, int j ) throws Exception;
public String getAnalysisName();
/** return true is getScore(a,i,j) == getScore( a, j, i )
*/
public boolean isSymmetrical();
/** return true if a low score indicates high covariance or conservation.
* return false if a high score indicates high covariance or conservation.
*/
public boolean reverseSort();
public Alignment getAlignment();
}
| 1,545 | 33.355556 | 97 | java |
cobs | cobs-master/cobs/covariance/algorithms/RandomScore.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.io.*;
import java.util.*;
import covariance.datacontainers.*;
public class RandomScore implements ScoreGenerator
{
public static final String RANDOM_NAME = "random";
Random random = new Random();
String idString;
private final Alignment a;
@Override
public Alignment getAlignment()
{
return a;
}
public static void main(String[] args) throws Exception
{
if ( args.length != 2 )
{
System.out.println( "Usage RandomScore inAlignment outFile" );
return;
}
Alignment a = new Alignment("1", new File( args[0]), false );
RandomScore rScore = new RandomScore();
BufferedWriter writer = new BufferedWriter( new FileWriter( new File(
args[1] )));
writer.write( "i\tj\tscore\n");
for ( int i =0; i < a.getNumColumnsInAlignment(); i++ )
if ( a.columnHasValidResidue(i) )
for ( int j = i + 1; j < a.getNumColumnsInAlignment(); j++ )
if ( a.columnHasValidResidue(j) )
writer.write( i + "\t" + j + "\t" + rScore.getScore(a, i, j) + "\n" );
writer.flush(); writer.close();
}
public Double getScore( Alignment a, int i, int j ) throws Exception
{
return random.nextDouble();
}
public RandomScore()
{
this(RANDOM_NAME, null);
}
public RandomScore(String idString, Alignment a)
{
this.idString = idString;
this.a = a;
}
public String getAnalysisName()
{
return idString;
}
public boolean isSymmetrical()
{
return true;
}
public boolean reverseSort()
{
return true;
}
}
| 2,185 | 22.010526 | 80 | java |
cobs | cobs-master/cobs/covariance/algorithms/ELSCCovariance.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import covariance.datacontainers.Alignment;
public class ELSCCovariance implements ScoreGenerator
{
private ELSCCovarianceSubAlignment lastSubAlignment = null;
private int lastI = -999;
private Alignment a;
char[] mostFrequentResidues;
String analysisID;
@Override
public Alignment getAlignment()
{
return a;
}
public ELSCCovariance(Alignment a) throws Exception
{
this(a, "ELSC");
}
public ELSCCovariance(Alignment a, String analysisID) throws Exception
{
this.a = a;
this.mostFrequentResidues= Alignment.getMostFrequentResidues(a);
this.analysisID = analysisID;
}
public String getAnalysisName()
{
return analysisID;
}
/** This will work a lot faster if you call all the j's for the same i since the last
* called subalignment i is cached
*/
public Double getScore(Alignment a, int i, int j) throws Exception
{
if ( this.a != a )
throw new Exception("Unexpected alignment");
if ( lastSubAlignment == null || lastI != i )
{
lastSubAlignment = new ELSCCovarianceSubAlignment( a, i, mostFrequentResidues[i]);
lastI = i;
}
return lastSubAlignment.getCovarianceScores()[j];
}
public boolean isSymmetrical()
{
return false;
}
public boolean reverseSort()
{
return false;
}
public static void main(String[] args) throws Exception
{
if ( args.length != 2 )
{
System.out.println( "Usage ELSCCovariance inAlignment outFile" );
return;
}
Alignment a = new Alignment("1", new File( args[0]), false );
ELSCCovariance elsc = new ELSCCovariance(a);
BufferedWriter writer = new BufferedWriter( new FileWriter( new File(
args[1] )));
writer.write( "i\tj\tscore\n");
for ( int i =0; i < a.getNumColumnsInAlignment(); i++ )
if ( a.columnHasValidResidue(i) )
for ( int j = i + 1; j < a.getNumColumnsInAlignment(); j++ )
if ( a.columnHasValidResidue(j) )
writer.write( i + "\t" + j + "\t" + elsc.getScore(a, i, j) + "\n" );
writer.flush(); writer.close();
}
}
| 2,773 | 24.925234 | 87 | java |
cobs | cobs-master/cobs/covariance/algorithms/AbsoluteValueFileScoreGenerator.java |
/**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.io.File;
import covariance.datacontainers.Alignment;
/*
* Just returns the absolute value of a cached file for score generators
*/
public class AbsoluteValueFileScoreGenerator extends FileScoreGenerator
{
public AbsoluteValueFileScoreGenerator(String name, File file, Alignment a) throws Exception
{
super(name,file,a);
}
@Override
public Double getScore(Alignment a, int i, int j) throws Exception
{
return Math.abs(super.getScore(a, i, j));
}
@Override
public String getAnalysisName()
{
return "Abs" + super.getAnalysisName();
}
}
| 1,246 | 26.711111 | 93 | java |
cobs | cobs-master/cobs/covariance/algorithms/FileScoreGenerator.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.GZIPInputStream;
import covariance.datacontainers.Alignment;
public class FileScoreGenerator implements ScoreGenerator
{
private final String name;
private final ConcurrentHashMap<String, Double> scores = new ConcurrentHashMap<String,Double>();
private final Alignment a;
private final boolean isSymmetrical;
private final boolean reverseSort;
private int lastI;
private int lastJ;
@Override
/*
* Assumes i < j
*/
public Double getScore(Alignment a, int i, int j) throws Exception
{
Double score = scores.get(i + "@" + j);
if( score == null)
{
throw new Exception("Could not find " + i + " " + j + " last vals= " + lastI + " " + lastJ);
}
return score;
}
public int getNumScores()
{
return scores.size();
}
@Override
public Alignment getAlignment()
{
return a;
}
@Override
public String getAnalysisName()
{
return name;
}
@Override
public boolean isSymmetrical()
{
return isSymmetrical;
}
@Override
public boolean reverseSort()
{
return reverseSort;
}
public FileScoreGenerator(String name, File file, Alignment a) throws Exception
{
this(name,file,a,true,false);
}
public FileScoreGenerator(String name, String filepath, Alignment a) throws Exception
{
this(name,new File(filepath),a,true,false);
}
public FileScoreGenerator(String name, File file, Alignment a, boolean isSymmetrical, boolean reverseSort) throws Exception
{
this.name = name;
BufferedReader reader = file.getName().toLowerCase().endsWith("gz") ?
new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( file )))) :
new BufferedReader(new FileReader(file)) ;
reader.readLine();
for(String s= reader.readLine(); s!= null; s= reader.readLine())
{
StringTokenizer sToken = new StringTokenizer(s);
if( sToken.countTokens() > 3)
throw new Exception("Parsing error");
if( sToken.countTokens() == 3)
{
int i = Integer.parseInt(sToken.nextToken());
int j = Integer.parseInt(sToken.nextToken());
double score = Double.parseDouble(sToken.nextToken());
String key = i + "@" + j;
if( scores.containsKey(key) )
throw new Exception("Parsing error");
scores.put(key,score);
lastI = i;
lastJ = j;
}
}
this.a = a;
this.isSymmetrical = isSymmetrical;
this.reverseSort = reverseSort;
reader.close();
}
}
| 3,334 | 23.343066 | 124 | java |
cobs | cobs-master/cobs/covariance/algorithms/PNormalize.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.algorithms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import utils.Avevar;
import covariance.datacontainers.Alignment;
public class PNormalize implements ScoreGenerator
{
private final HashMap<Integer, Double> averages = new HashMap<Integer, Double>();
private final double grandAverage;
private final ScoreGenerator wrappedMetric;
/*
* Todo: Improve the concurrency. This constructor takes a long time to complete,
* blokcing progress other threads from getting spawned.
*/
public PNormalize(ScoreGenerator wrappedMetric) throws Exception
{
if(! wrappedMetric.isSymmetrical())
throw new Exception("underlying algorithm must be symmetrical");
this.wrappedMetric = wrappedMetric;
double sum =0;
int n=0;
HashMap<Integer, List<Double>> map = new HashMap<Integer, List<Double>>();
for( int x=0; x < wrappedMetric.getAlignment().getNumColumnsInAlignment() -1; x++)
for(int y=x +1; y < wrappedMetric.getAlignment().getNumColumnsInAlignment();y++)
{
double score = wrappedMetric.getScore(wrappedMetric.getAlignment(), x, y);
n++;
sum += score;
addToMap(map, x, score);
addToMap(map, y, score);
}
grandAverage = sum / n;
for( Integer i : map.keySet() )
averages.put(i, new Avevar(map.get(i)).getAve());
}
private static void addToMap( HashMap<Integer, List<Double>> map, int col, double score )
{
List<Double> list = map.get(col);
if(list==null)
{
list = new ArrayList<Double>();
map.put(col, list);
}
list.add(score);
}
@Override
public Alignment getAlignment()
{
return wrappedMetric.getAlignment();
}
@Override
public Double getScore(Alignment a, int i, int j) throws Exception
{
return wrappedMetric.getScore(a, i, j) - averages.get(i) * averages.get(j) / grandAverage;
}
@Override
public String getAnalysisName()
{
return wrappedMetric.getAnalysisName() + "_PNormalInitial";
}
@Override
public boolean isSymmetrical()
{
return true;
}
@Override
public boolean reverseSort()
{
return wrappedMetric.reverseSort();
}
}
| 2,766 | 24.859813 | 92 | java |
cobs | cobs-master/cobs/covariance/datacontainers/PdbFileWrapper.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import utils.ConfigReader;
import covariance.parsers.PdbParser;
public class PdbFileWrapper
{
private String pdbId;
private List pdbChains = new ArrayList();
private String experimentMethod;
public PdbFileWrapper( File pdbFile ) throws Exception
{
new PdbParser(pdbFile.getAbsolutePath() , this);
}
public PdbFileWrapper( String fourCharId ) throws Exception
{
this(new File( ConfigReader.getPdbDir()+
File.separator + fourCharId + ".txt") );
}
public List getPdbChains()
{
return pdbChains;
}
public String getFourCharId()
{
return pdbId;
}
public void setPdbId(String pdbId)
{
this.pdbId = pdbId;
}
public void addChain(PdbChain pdbChain )
{
pdbChains.add(pdbChain);
}
public PdbChain getChain( Character chainChar )
{
return getChain( chainChar.charValue());
}
public PdbChain getChain( char chainChar )
{
for ( Iterator i = this.pdbChains.iterator();
i.hasNext(); )
{
PdbChain pdbChain = ( PdbChain ) i.next();
if ( pdbChain.getChainChar() == chainChar )
return pdbChain;
}
return null;
}
public int getLongestLength()
{
int longestLength = -1;
for ( int x=0; x < this.pdbChains.size(); x++ )
{
PdbChain chain= (PdbChain) this.pdbChains.get(x);
longestLength = Math.max( longestLength, chain.getPdbResidues().size() );
}
return longestLength;
}
public String getExperimentMethod()
{
return experimentMethod;
}
public void setExperimentMethod(String experimentMethod)
{
this.experimentMethod = experimentMethod;
}
}
| 2,349 | 20.363636 | 77 | java |
cobs | cobs-master/cobs/covariance/datacontainers/PdbResidue.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import utils.SequenceUtils;
public class PdbResidue implements Comparable
{
private char pdbChar;
private int pdbPosition;
private PdbChain parentChain;
private List pdbAtoms = new ArrayList();
private int numNeighbors = -1;
private int numHydrophobicNeighbors = -1;
private PdbAtom cbAtom;
private boolean isHydrophobic;
public static final float NEIGHBOR_DISTANCE_CUTOFF=10;
public static final char BLANK_CHAR='-';
public static final int BLANK_POSITION=-99;
public PdbChain getParentChain()
{
return parentChain;
}
public boolean isHydrophobic()
{
return isHydrophobic;
}
public void generateNeighborList(List pdbChains)
{
this.numNeighbors = 0;
this.numHydrophobicNeighbors = 0;
for ( Iterator i = pdbChains.iterator();
i.hasNext(); )
{
PdbChain chain = (PdbChain) i.next();
for ( Iterator i2 = chain.getPdbResidues().iterator();
i2.hasNext(); )
{
PdbResidue otherResidue = (PdbResidue) i2.next();
if ( otherResidue.cbAtom != null &&
this != otherResidue &&
this.cbAtom.getDistance( otherResidue.cbAtom ) < NEIGHBOR_DISTANCE_CUTOFF )
{
this.numNeighbors++;
if ( otherResidue.isHydrophobic )
this.numHydrophobicNeighbors++;
}
}
}
}
/** call generateNeighborList before calling this method.
*/
public int getNumNeighbors() throws Exception
{
if ( this.numNeighbors == -1 )
throw new Exception("Error! call generateNeighborList() before calling this method" );
return this.numNeighbors;
}
/** call generateNeighborList before calling this method.
*/
public int getNumHydrophicNeighbors() throws Exception
{
if ( this.numHydrophobicNeighbors== -1 )
throw new Exception("Error! call generateNeighborList() before calling this method" );
return this.numHydrophobicNeighbors;
}
public char getPdbChar()
{
return pdbChar;
}
public int getPdbPosition()
{
return pdbPosition;
}
public void addPdbAtom( PdbAtom pdbAtom )
{
if ( pdbChar == 'G' )
{
if (pdbAtom.getAtomName().equals("CA") )
this.cbAtom = pdbAtom;
}
else
{
if ( pdbAtom.getAtomName().equals("CB") )
this.cbAtom = pdbAtom;
}
this.pdbAtoms.add( pdbAtom );
}
public PdbResidue( char pdbChar, int pdbPosition, PdbChain parentChain )
{
this.pdbChar = pdbChar;
this.pdbPosition = pdbPosition;
this.parentChain = parentChain;
if (SequenceUtils.isHydrophicChar( this.pdbChar) )
{
this.isHydrophobic = true;
}
else
{
this.isHydrophobic = false;
}
}
public int getTotalNumberAtomAtomContactsFromChains( List pdbChains ) throws Exception
{
int sum = 0;
for ( Iterator i = pdbChains.iterator();
i.hasNext(); )
{
PdbChain chain = (PdbChain) i.next();
sum += getTotalNumberAtomAtomContacts( chain.getPdbResidues() );
}
return sum;
}
private int getTotalNumberAtomAtomContacts( Collection pdbResidues ) throws Exception
{
int sum = 0;
for ( Iterator i = pdbResidues.iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue) i.next();
if ( this != pdbResidue )
{
sum+= getNumAtomAtomContacts(pdbResidue);
}
}
return sum;
}
/** Returns the number of atoms within 5A of each other between this residue and otherResidue
*/
private int getNumAtomAtomContacts( PdbResidue otherResidue ) throws Exception
{
int returnInt =0;
for ( Iterator i1 = this.pdbAtoms.iterator();
i1.hasNext(); )
{
PdbAtom thisAtom = (PdbAtom) i1.next();
for (Iterator i2= otherResidue.pdbAtoms.iterator();
i2.hasNext(); )
{
PdbAtom otherAtom = (PdbAtom) i2.next();
if ( thisAtom.getDistance( otherAtom) <= 5.0f )
returnInt++;
}
}
return returnInt;
}
public float getAverageTemperature() throws Exception
{
if ( this.pdbAtoms.size() == 0 )
throw new Exception("Error! No atoms in residue ");
float sum =0;
for ( Iterator i = this.pdbAtoms.iterator();
i.hasNext(); )
{
PdbAtom atom = (PdbAtom) i.next();
sum += atom.getTemperature();
}
return sum / this.pdbAtoms.size();
}
/** todo: Make more efficient
*
* returns null if the atom can't be found
*/
public PdbAtom getAtom( String atomName )
{
for ( Iterator i = pdbAtoms.iterator();
i.hasNext();
)
{
PdbAtom atom = (PdbAtom) i.next();
if ( atom.getAtomName().equals(atomName) )
return atom;
}
return null;
}
public PdbAtom getCbAtom()
{
return this.cbAtom;
}
public List getPdbAtoms()
{
return pdbAtoms;
}
public int compareTo(Object o)
{
PdbResidue other = (PdbResidue ) o;
return Float.compare(this.pdbPosition, other.pdbPosition);
}
@Override
public String toString() {
return "PdbResidue [pdbChar=" + pdbChar + "]";
}
}
| 5,649 | 20.899225 | 95 | java |
cobs | cobs-master/cobs/covariance/datacontainers/PdbChain.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class PdbChain
{
private char chainChar;
private HashSet pdbResidues = new HashSet();
private PdbFileWrapper pdbFile;
private int highestPdbResiduePosition = -1;
public PdbChain( char chainId, PdbFileWrapper pdbFile )
{
this.chainChar = chainId;
this.pdbFile = pdbFile;
}
public void addResidue(PdbResidue pdbResidue)
{
this.pdbResidues.add( pdbResidue );
if( highestPdbResiduePosition < pdbResidue.getPdbPosition() )
highestPdbResiduePosition = pdbResidue.getPdbPosition();
}
public String getSequence()
{
StringBuffer buff = new StringBuffer();
List aList = new ArrayList( pdbResidues);
Collections.sort( aList );
for ( int x=0; x< aList.size(); x++ )
{
PdbResidue reside = (PdbResidue) aList.get(x);
buff.append( reside.getPdbChar());
}
return buff.toString();
}
public char getChainChar()
{
return chainChar;
}
public PdbFileWrapper getPdbFile()
{
return pdbFile;
}
public HashSet getPdbResidues()
{
return pdbResidues;
}
/** Todo: Make more efficient
*/
public PdbResidue getPdbResidueByPdbPosition( int pdbPosition )
{
for ( Iterator i = pdbResidues.iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue) i.next();
if ( pdbResidue.getPdbPosition() == pdbPosition )
return pdbResidue;
}
return null;
}
public int getHighestPdbResiduePosition()
{
return highestPdbResiduePosition;
}
@Override
public String toString() {
return "PdbChain [chainChar=" + chainChar + ", pdbResidues="
+ pdbResidues + ", pdbFile=" + pdbFile
+ ", highestPdbResiduePosition=" + highestPdbResiduePosition
+ "]";
}
}
| 2,486 | 22.242991 | 74 | java |
cobs | cobs-master/cobs/covariance/datacontainers/PairColors.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import java.util.Collection;
import java.util.Iterator;
public class PairColors
{
private int xPos;
private int yPos;
private char xChar;
private char yChar;
private String colorString;
public static String DEFAULT_COLOR_STRING= "black";
public PairColors(int xPos, char xChar, int yPos, char yChar, String colorString)
{
this.xPos = xPos;
this.xChar = xChar;
this.yPos = yPos;
this.yChar = yChar;
this.colorString = colorString;
}
public static String getColorStringAsRange( Collection pairColors, AlignmentLine aLine, int aPos )
{
String aSequence = aLine.getSequence();
for ( Iterator i = pairColors.iterator();
i.hasNext(); )
{
PairColors pColor = (PairColors) i.next();
if ( aPos >= pColor.getXPos() && aPos <= pColor.getYPos())
{
return pColor.getColorString();
}
}
return DEFAULT_COLOR_STRING;
}
public static String getColorString( Collection pairColors, AlignmentLine aLine, int aPos )
{
String aSequence = aLine.getSequence();
for ( Iterator i = pairColors.iterator();
i.hasNext(); )
{
PairColors pColor = (PairColors) i.next();
if ( aPos == pColor.getXPos() || aPos == pColor.getYPos())
{
if ( aSequence.charAt(pColor.getXPos()) == pColor.getXChar() &&
aSequence.charAt(pColor.getYPos() ) == pColor.getYChar() )
return pColor.getColorString();
}
}
return DEFAULT_COLOR_STRING;
}
public boolean isMatch( int xPos, char xChar, int yPos, char yChar )
{
if ( this.xPos != xPos )
return false;
if ( this.xChar != xChar )
return false;
if ( this.yPos != yPos )
return false;
if ( this.yChar != yChar )
return false;
return true;
}
public static String getColorString( Collection pairColors, int xPos, char xChar, int yPos, char yChar )
{
for ( Iterator i = pairColors.iterator();
i.hasNext(); )
{
PairColors pColor = (PairColors) i.next();
if ( pColor.isMatch(xPos, xChar, yPos, yChar))
return pColor.getColorString();
}
return DEFAULT_COLOR_STRING;
}
public String getColorString()
{
return colorString;
}
public char getXChar()
{
return xChar;
}
public int getXPos()
{
return xPos;
}
public char getYChar()
{
return yChar;
}
public int getYPos()
{
return yPos;
}
}
| 3,000 | 21.066176 | 106 | java |
cobs | cobs-master/cobs/covariance/datacontainers/PdbAtom.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
public class PdbAtom
{
private int serialNumber;
private String atomName;
private String residueName;
private char chainID;
private int residueSequenceNumber;
private float x, y, z;
private float occupancy;
private float temperature;
public int getSerialNumber()
{
return this.serialNumber;
}
public float getTemperature()
{
return this.temperature;
}
public double getDistance( PdbAtom otherAtom)
{
float xDiff = this.getX() - otherAtom.getX();
xDiff = xDiff * xDiff;
float yDiff = this.getY() - otherAtom.getY();
yDiff = yDiff * yDiff;
float zDiff = this.getZ() - otherAtom.getZ();
zDiff = zDiff * zDiff;
return Math.sqrt( xDiff + yDiff + zDiff ) ;
}
public String getAtomName()
{
return this.atomName;
}
public String getResidueName()
{
return this.residueName;
}
public char getChainId()
{
return this.chainID;
}
public float getOccupancy()
{
return this.occupancy;
}
public int getResidueSequenceNumber()
{
return this.residueSequenceNumber;
}
public float getX()
{
return this.x;
}
public float getY()
{
return this.y;
}
public float getZ()
{
return this.z;
}
public PdbAtom( String pdbAtomLine ) throws Exception
{
if ( ! pdbAtomLine.startsWith("ATOM") )
throw new Exception("Error! Expecting the atom line to start with ATOM");
this.serialNumber = Integer.parseInt( pdbAtomLine.substring(6,11).trim() );
this.atomName = pdbAtomLine.substring( 12, 16).trim();
this.residueName = pdbAtomLine.substring(17,20).trim();
this.chainID = pdbAtomLine.substring( 21, 22 ).charAt(0);
this.residueSequenceNumber = Integer.parseInt( pdbAtomLine.substring(22,26).trim() );
this.x = Float.parseFloat(pdbAtomLine.substring(30,38).trim() );
this.y = Float.parseFloat( pdbAtomLine.substring(38,46).trim() );
this.z = Float.parseFloat( pdbAtomLine.substring(46,54).trim());
this.occupancy = Float.parseFloat( pdbAtomLine.substring(54, 60).trim() );
this.temperature = Float.parseFloat( pdbAtomLine.substring(60,66).trim() );
}
}
| 2,776 | 23.147826 | 87 | java |
cobs | cobs-master/cobs/covariance/datacontainers/SangerPDBpfamMappingSingleLine.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import java.io.CharConversionException;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.util.InputMismatchException;
import java.util.Scanner;
import org.omg.IOP.CodecPackage.TypeMismatch;
public class SangerPDBpfamMappingSingleLine
{
final private String pdbID;
final private Character chainID;
final private Integer pdbResNumStart;
final private Integer pdbResNumEnd;
final private String pFAMacc;
final private String pFAMname;
final private String pFAMdesc;
final private Double eValue;
/**
* @param pdbID
* @param chainID
* @param pdbResNumStart
* @param pdbResNumEnd
* @param pFAMacc
* @param pFAMname
* @param pFAMdesc
* @param eValue
* @throws CharConversionException
* @throws TypeMismatch
*/
public SangerPDBpfamMappingSingleLine(Scanner reader ) throws CharConversionException, TypeMismatch {
this.pdbID = reader.next();
if (pdbID.startsWith("PDB_I")){
throw new StringIndexOutOfBoundsException("We have found the first header line, skipping the parse as we should.");
}
if (pdbID.length() !=4){
throw new IndexOutOfBoundsException("PDB Wrong length");
}
String tempChain = reader.next();
if (tempChain.length() != 1) {
throw new TypeMismatch("Chain is too long");
}
this.chainID = tempChain.charAt(0);
if (Character.isDigit(chainID)){
throw new CharConversionException("We had a digit in place of a char for chainID");
}
this.pdbResNumStart = reader.nextInt();
if (pdbResNumStart < 0) {
throw new IndexOutOfBoundsException("PDB supposedly starts before any sensible first sequence");
}
this.pdbResNumEnd = reader.nextInt();
if (pdbResNumEnd <= pdbResNumStart){
throw new IndexOutOfBoundsException("Last residue is before the first residue");
}
this.pFAMacc = reader.next();
this.pFAMname = reader.next();
this.pFAMdesc = reader.next();
Double tempEvalue = -99D;
//Having issues with consistent behavior of Scanner for parsing scientific values. This might help us debug, or might allow us to just move forward.
try {
String eValueS = reader.next();
tempEvalue = Double.parseDouble(eValueS);
} catch (InputMismatchException e) {
throw new InputMismatchException("Problem with parsing the double for e-value.");
}
finally {}
if (tempEvalue == -99D){
throw new InputMismatchException("We couldn't convert the e-value correctly from a String (Workaround)");
}
this.eValue = tempEvalue;
}
public String getPdbID() {
return pdbID;
}
public Character getChainID() {
return chainID;
}
public Integer getPdbResNumStart() {
return pdbResNumStart;
}
public Integer getPdbResNumEnd() {
return pdbResNumEnd;
}
public String getpFAMacc() {
return pFAMacc;
}
public String getpFAMname() {
return pFAMname;
}
public String getpFAMdesc() {
return pFAMdesc;
}
public Double geteValue() {
return eValue;
}
@Override
public String toString() {
java.lang.reflect.Field[] fields = getClass().getDeclaredFields();
AccessibleObject.setAccessible(fields,true);
StringBuffer sb = new StringBuffer();
sb.append("Class: " + this.getClass().getName() + "\n");
for (java.lang.reflect.Field field : fields) {
Object value = null;
try {
value = field.get(this);
} catch (IllegalAccessException e) {continue;}
sb.append("\tField \"" + field.getName() + "\"\n");
Class fieldType = field.getType();
sb.append("\t\tType: ");
if (fieldType.isArray()) {
Class subType = fieldType.getComponentType();
int length = Array.getLength(value);
sb.append(subType.getName() + "[" + length + "]" + "\n");
for (int i = 0; i < length; i ++) {
Object obj = Array.get(value,i);
sb.append("\t\tValue " + i + ": " + obj + "\n");
}
} else {
sb.append(fieldType.getName() + "\n");
sb.append("\t\tValue: ");
sb.append((value == null) ? "NULL" : value.toString());
sb.append("\n");
}
}
return sb.toString();
}
}
| 4,856 | 28.083832 | 151 | java |
cobs | cobs-master/cobs/covariance/datacontainers/ReferenceSequenceResidue.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ReferenceSequenceResidue
{
private char referenceChar;
private int alignmentPosition;
private List linkedPdbResidues = new ArrayList();
public boolean allMatches()
{
if ( referenceChar == Alignment.GAP_CHAR )
return false;
for ( Iterator i = linkedPdbResidues.iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue) i.next();
if ( pdbResidue.getPdbChar() != referenceChar || pdbResidue.getCbAtom() == null )
return false;
}
return true;
}
public int getAlignmentPosition()
{
return alignmentPosition;
}
public List getLinkedPdbResidues()
{
return linkedPdbResidues;
}
public char getReferenceChar()
{
return referenceChar;
}
public PdbResidue getLinkedPdbResidue( char chainChar)
{
for ( Iterator i = this.linkedPdbResidues.iterator();
i.hasNext(); )
{
PdbResidue pdbRes = (PdbResidue) i.next();
if ( pdbRes.getParentChain().getChainChar() == chainChar )
return pdbRes;
}
return null;
}
public double getMinCbDistance( ReferenceSequenceResidue otherResidue ) throws Exception
{
double min = Double.MAX_VALUE;
for ( Iterator i = this.linkedPdbResidues.iterator();
i.hasNext(); )
{
PdbResidue iResidue = (PdbResidue) i.next();
PdbAtom iAtom = iResidue.getCbAtom();
for ( Iterator j = otherResidue.linkedPdbResidues.iterator();
j.hasNext(); )
{
PdbResidue jResidue = (PdbResidue) j.next();
PdbAtom jAtom = jResidue.getCbAtom();
double score = iAtom.getDistance( jAtom);
if ( score < min )
min = score;
}
}
if ( min == Double.MAX_VALUE )
throw new Exception("Comparison not valid");
return min;
}
public double getAvgNumAtomAtomContacts( List pdbChains ) throws Exception
{
double sum = 0;
int n =0;
for ( Iterator i = this.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue) i.next();
sum += pdbResidue.getTotalNumberAtomAtomContactsFromChains( pdbChains);
n++;
}
return sum / n;
}
public double getAvgNumContacts( ReferenceSequenceResidue otherResidue ) throws Exception
{
double sum = 0;
int n = 0;
for ( Iterator i = this.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue ) i.next();
sum += pdbResidue.getNumNeighbors();
n++;
}
for ( Iterator i = otherResidue.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue ) i.next();
sum += pdbResidue.getNumNeighbors();
n++;
}
return sum/n;
}
public double getAvgNumContacts() throws Exception
{
double sum = 0;
int n = 0;
for ( Iterator i = this.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue ) i.next();
sum += pdbResidue.getNumNeighbors();
n++;
}
return sum/n;
}
public double getAvgNumHydrophobicContacts() throws Exception
{
double sum = 0;
int n = 0;
for ( Iterator i = this.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue ) i.next();
sum += pdbResidue.getNumHydrophicNeighbors();
n++;
}
return sum/n;
}
public double getAvgNumHydrophobicContacts( ReferenceSequenceResidue otherResidue ) throws Exception
{
double sum = 0;
int n = 0;
for ( Iterator i = this.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue ) i.next();
sum += pdbResidue.getNumHydrophicNeighbors();
n++;
}
for ( Iterator i = otherResidue.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue ) i.next();
sum += pdbResidue.getNumHydrophicNeighbors();
n++;
}
return sum/n;
}
public double getAvgTemperature()
{
double sum = 0;
int n = 0;
List atomList = new ArrayList();
for ( Iterator i = this.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue ) i.next();
atomList.addAll( pdbResidue.getPdbAtoms() );
}
for ( Iterator i = atomList.iterator();
i.hasNext(); )
{
PdbAtom atom = (PdbAtom) i.next();
sum += atom.getTemperature();
n++;
}
return sum/n;
}
public double getAvgTemperature( ReferenceSequenceResidue otherResidue )
{
double sum = 0;
int n = 0;
List atomList = new ArrayList();
for ( Iterator i = this.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue ) i.next();
atomList.addAll( pdbResidue.getPdbAtoms() );
}
for ( Iterator i = otherResidue.getLinkedPdbResidues().iterator();
i.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue ) i.next();
atomList.addAll( pdbResidue.getPdbAtoms() );
}
for ( Iterator i = atomList.iterator();
i.hasNext(); )
{
PdbAtom atom = (PdbAtom) i.next();
sum += atom.getTemperature();
n++;
}
return sum/n;
}
public ReferenceSequenceResidue( char referenceChar,
int alignmentPosition )
{
this.referenceChar = referenceChar;
this.alignmentPosition = alignmentPosition;
}
public void addLinkedPdbResidue( PdbResidue pdbResidue )
{
this.linkedPdbResidues.add(pdbResidue);
}
}
| 6,077 | 21.428044 | 101 | java |
cobs | cobs-master/cobs/covariance/datacontainers/ReferenceSequence.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ReferenceSequence
{
private List referenceSequenceResidues = new ArrayList();
public List getReferenceSequenceResidues()
{
return referenceSequenceResidues;
}
public void addReferenceSequenceResidue( ReferenceSequenceResidue refSequenceResidue )
{
this.referenceSequenceResidues.add( refSequenceResidue );
}
public ReferenceSequenceResidue getRefSeqByAlignmentPosition( int alignmentPosition) throws Exception
{
for ( Iterator i = referenceSequenceResidues.iterator();
i.hasNext(); )
{
ReferenceSequenceResidue rSeqResidue =
(ReferenceSequenceResidue) i.next();
if ( rSeqResidue.getAlignmentPosition() == alignmentPosition )
return rSeqResidue;
}
return null;
}
public ReferenceSequenceResidue getRefSeqByPdbPosition( char pdbChainChar, int pdbPosition )
{
for ( Iterator i = referenceSequenceResidues.iterator();
i.hasNext(); )
{
ReferenceSequenceResidue rSeqResidue = (ReferenceSequenceResidue)i.next();
for ( Iterator i2= rSeqResidue.getLinkedPdbResidues().iterator();
i2.hasNext(); )
{
PdbResidue pdbResidue = (PdbResidue) i2.next();
if ( pdbResidue.getParentChain().getChainChar() == pdbChainChar &&
pdbResidue.getPdbPosition() == pdbPosition )
return rSeqResidue;
}
}
return null;
}
public void calculateNeighbors(PdbFileWrapper pdbFileWrapper) throws Exception
{
for ( Iterator i = referenceSequenceResidues.iterator();
i.hasNext(); )
{
ReferenceSequenceResidue rSeqResidue = ( ReferenceSequenceResidue ) i.next();
if ( rSeqResidue.allMatches() )
{
for ( Iterator i2 = rSeqResidue.getLinkedPdbResidues().iterator();
i2.hasNext(); )
{
PdbResidue linkedResidue = ( PdbResidue )i2.next();
linkedResidue.generateNeighborList( pdbFileWrapper.getPdbChains() );
}
}
}
}
}
| 2,640 | 27.706522 | 102 | java |
cobs | cobs-master/cobs/covariance/datacontainers/AlignmentLine.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import utils.MapResiduesToIndex;
public class AlignmentLine
{
public static final Character GAP_CHAR = new Character( '-');
private final String identifier;
private final String sequence;
private final int numValidChars;
public String getIdentifier()
{
return identifier;
}
public String getSequence()
{
return sequence;
}
public AlignmentLine( String identifier, String sequence )
{
this.identifier = identifier;
this.sequence = sequence;
int vChars = 0;
for ( int x=0; x< sequence.length(); x++ )
if ( MapResiduesToIndex.isValidResidueChar( sequence.charAt(x) ) )
vChars++;
numValidChars = vChars;
}
public String getUngappedSequence() throws Exception
{
StringBuffer buff = new StringBuffer();
String capSequence = this.sequence.toUpperCase();
for ( int x=0; x< capSequence.length(); x++ )
{
char c = capSequence.charAt( x );
if ( MapResiduesToIndex.isValidResidueChar( c ) )
buff.append(c);
}
return buff.toString();
}
public String toString()
{
return identifier + "\t" + sequence;
}
public int getNumValidChars()
{
return numValidChars;
}
}
| 1,830 | 22.779221 | 74 | java |
cobs | cobs-master/cobs/covariance/datacontainers/Alignment.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import utils.MapResiduesToIndex;
import covariance.algorithms.ConservationSum;
import covariance.parsers.FastaSequence;
import covariance.parsers.PFamPdbAnnotationParser;
public class Alignment
{
public static final Character GAP_CHARACTER = new Character( '-');
public static final char GAP_CHAR= GAP_CHARACTER.charValue();
private final String alignmentID;
private final List<AlignmentLine> alignmentLines;
private final int numColumns;
private final int[][] counts;
private final float[] frequencies;
private final int[] totalValid;
private final String[] columnStrings;
// guarded by this
private PFamPdbAnnotationParser pdbIds[];
public String getAligmentID()
{
return alignmentID;
}
public boolean columnHasValidResidue( int col ) throws Exception
{
if ( getRatioValid(col) > 0f )
return true;
return false;
}
/** See Henikoff and Henikoff, J. Mol. Biol. 1994, 243, 574-578.
*
* Returns the array of weights, which probably will only be used for testing
**/
/*
public synchronized double[] adjustFrequenciesByWeights() throws Exception
{
getFrequencies(); // initialize
double[] weights = new double[ getNumSequencesInAlignment() ];
double weightSum = 0;
for ( int col=0; col < getNumColumnsInAlignment(); col++ )
{
int r =0;
for ( int res=0; res < MapResiduesToIndex.NUM_VALID_RESIDUES; res++ )
if ( counts[col][res] > 0 )
r++;
System.out.println("Got r of " + r + " for col " + col);
for ( int row=0; row< getNumSequencesInAlignment(); row++ )
{
String aSequence = ((AlignmentLine) getAlignmentLines().get(row)).getSequence();
char c = aSequence.charAt(col);
if ( MapResiduesToIndex.isValidResidueChar(c) )
{
weights[row] += 1f / ( r * counts[col][MapResiduesToIndex.getIndex(c)] );
}
}
}
for ( int x=0; x< weights.length; x++ )
weightSum += weights[x];
for ( int x=0; x< weights.length; x++ )
{
weights[x] /= weightSum;
}
this.frequencies = new float[ MapResiduesToIndex.NUM_VALID_RESIDUES];
int totalNum =0;
for ( int res = 0; res < MapResiduesToIndex.NUM_VALID_RESIDUES; res++ )
{
for ( int row = 0; row < getNumSequencesInAlignment(); row++ )
{
String aSequence = ((AlignmentLine) getAlignmentLines().get(row)).getSequence();
for ( int col=0; col < getNumColumnsInAlignment(); col++ )
{
char c = aSequence.charAt(col);
if ( MapResiduesToIndex.isValidResidueChar(c) )
{
totalNum++;
this.frequencies[res] += weights[row] * getNumSequencesInAlignment();
}
}
}
}
for ( int x=0; x< MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
this.frequencies[x] /= totalNum;
return weights;
}*/
//guarded by this
private List<FastaSequence> fastaList = null;
/*
* Lazy initialized but synchronized
*/
public synchronized List<FastaSequence> getAsFastaSequenceList() throws Exception
{
if( fastaList == null)
{
List<FastaSequence> list = new ArrayList<FastaSequence>();
for( AlignmentLine aLine : alignmentLines)
{
list.add(new FastaSequence( aLine.getIdentifier(), aLine.getSequence() ));
}
fastaList = Collections.unmodifiableList(list);
}
return fastaList;
}
public float getMeanConservation( float cutoffRatio ) throws Exception
{
ConservationSum cSum = new ConservationSum(this);
float sum = 0;
int n =0;
for ( int x=0; x< this.numColumns; x++ )
{
if ( getRatioValid(x) >= cutoffRatio )
{
sum+= cSum.getScore(x);
n++;
}
}
return sum / n;
}
public void dumpAlignmentToConsole()
{
for( AlignmentLine aLine : alignmentLines)
System.out.println(aLine.getSequence());
}
public String getColumnAsString( int colPos ) throws Exception
{
return columnStrings[colPos];
}
/** removes any column in which the most conserved residue in that column
* is less than the cutoff ( cutoff should be between 0 and 1 )
*/
public Alignment getAlignmentWithRemovedUnconservedColumns(float cutoff ) throws Exception
{
boolean[] tossColumns = getTossColumns(cutoff);
List newAlignmentLines = getNewAlignmentLines(tossColumns);
Alignment newAlignment = new Alignment(this.getAligmentID(), newAlignmentLines);
newAlignment.setPdbIds( this.getPdbIds());
return newAlignment;
}
public void writeUngappedAsFasta(String file) throws Exception
{
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(file)));
for( AlignmentLine aLine : alignmentLines )
{
writer.write(">" + aLine.getIdentifier() + "\n");
writer.write(aLine.getSequence().replace(".", "").replace("-", "").toUpperCase() + "\n");
}
writer.flush(); writer.close();
}
public static Alignment getAlignmentFromFasta( File file ) throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader( file ));
List list= new ArrayList();
String nextLine = reader.readLine();
while ( nextLine != null )
{
list.add( new AlignmentLine( nextLine, reader.readLine() ));
nextLine = reader.readLine();
}
return new Alignment("fromFasta", list );
}
private List getNewAlignmentLines( boolean[] tossColumns )
{
List newAlignmentLines = new ArrayList();
for ( Iterator i = this.getAlignmentLines().iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
StringBuffer buff = new StringBuffer();
String oldSequence = aLine.getSequence();
for ( int x=0; x < oldSequence.length(); x++ )
if ( ! tossColumns[x] )
buff.append(oldSequence.charAt(x));
newAlignmentLines.add( new AlignmentLine( aLine.getIdentifier(), buff.toString()));
}
return newAlignmentLines;
}
/** Each tossColumn returns true if the most frequent residue in the column occurs
* in less than the cutoff.
*
* For example, if the cutoff value is .2, any column in which the most conserved residue
* is less than 20% of all valid residues in that column, will have a tossColumn of false.
*
* This is used for pertubation based covariation algorithms which require a minimal number
* of sequences in their pertubation.
*/
public boolean[] getTossColumns( float cutoff ) throws Exception
{
int[][] counts = getCounts();
if ( cutoff < 0 || cutoff > 1 )
throw new Exception("Illegal cutoff " + cutoff );
char[] mostFrequentChars = getMostFrequentResidues(this);
boolean[] tossColumn = new boolean[this.numColumns];
for ( int x=0; x< this.numColumns; x++ )
{
if ( ! MapResiduesToIndex.isValidResidueChar(mostFrequentChars[x]) )
{
tossColumn[x] = true;
}
else
{
float ratio =
((float)counts[x][MapResiduesToIndex.getIndex(mostFrequentChars[x])])
/ this.getNumSequencesInAlignment();
if ( ratio > cutoff )
tossColumn[x] = false;
else
tossColumn[x] = true;
}
}
return tossColumn;
}
/** Tosses the second of any two sequences that have a percent identity greater than or equal to the
* cutoff ( cutoff should be between 0 and 100 )
*/
public Alignment getFilteredAlignment(float cutoff) throws Exception
{
if ( cutoff > 100 )
throw new Exception("Error! Illegal cutoff " + cutoff);
List newLines = new ArrayList();
for ( Iterator i = this.getAlignmentLines().iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
if ( okToAdd(newLines, aLine, cutoff) )
newLines.add(aLine);
}
return new Alignment( this.getAligmentID(), newLines );
}
private boolean okToAdd( List lines, AlignmentLine aLine, float cutoff )
{
for ( Iterator i = lines.iterator();
i.hasNext(); )
{
AlignmentLine aListLine = (AlignmentLine) i.next();
if ( getPairwiseIdentity( aLine, aListLine ) >= cutoff )
return false;
}
return true;
}
public void writeUngappedSequencesAsFasta( File file ) throws Exception
{
BufferedWriter writer = new BufferedWriter( new FileWriter( file ));
writeUngappedSequencesAsFasta(writer);
writer.flush(); writer.close();
}
public void writeUngappedSequencesAsFasta( BufferedWriter writer ) throws Exception
{
for ( Iterator i = alignmentLines.iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
writer.write( ">" + aLine.getIdentifier() + "\n" );
writer.write( aLine.getUngappedSequence().toString() );
writer.write( "\n");
}
writer.flush();
}
public int getNumSequencesInAlignment()
{
return alignmentLines.size();
}
public int getNumColumnsInAlignment()
{
return numColumns;
}
public List<AlignmentLine> getAlignmentLines()
{
return this.alignmentLines;
}
public static float getAveragePairwiseIdentity( List alignmentLines )
{
float sum = 0;
int n =0;
for ( int x=0; x< alignmentLines.size(); x ++ )
{
AlignmentLine xLine = (AlignmentLine) alignmentLines.get(x);
for ( int y=x+1; y < alignmentLines.size(); y++)
{
AlignmentLine yLine = (AlignmentLine) alignmentLines.get(y);
sum += getPairwiseIdentity(xLine, yLine);
n++;
}
}
return sum / n;
}
public static float getPairwiseIdentity( AlignmentLine line1, AlignmentLine line2)
{
int length1 = 0;
int length2 = 0;
String sequence1 = line1.getSequence().toUpperCase();
String sequence2 = line2.getSequence().toUpperCase();
int numIdentical=0;
for ( int x=0; x< line1.getSequence().length(); x++ )
{
char c1 = sequence1.charAt(x);
char c2 = sequence2.charAt(x);
boolean c1Ok = MapResiduesToIndex.isValidResidueChar(c1);
boolean c2Ok = MapResiduesToIndex.isValidResidueChar(c2);
if ( c1Ok)
length1++;
if ( c2Ok )
length2++;
if ( c1Ok && c2Ok && c1 == c2 )
{
numIdentical++;
}
}
return 100 * ((float)numIdentical)/Math.min( length1, length2 );
}
public boolean containsAnAlignmentLine( String id )
{
for ( Iterator i = getAlignmentLines().iterator();
i.hasNext(); )
{
AlignmentLine aLine = ( AlignmentLine) i.next();
if ( aLine.getIdentifier().equals(id) )
return true;
}
return false;
}
public AlignmentLine getAnAlignmentLine(String id) throws Exception
{
for ( Iterator i = getAlignmentLines().iterator();
i.hasNext(); )
{
AlignmentLine aLine = ( AlignmentLine) i.next();
if ( aLine.getIdentifier().equals(id) )
return aLine;
}
throw new Exception("Could not find " + id );
}
public int getTotalNumValidColumns( float cutoff ) throws Exception
{
int sum = 0;
for ( int x=0; x< getNumColumnsInAlignment(); x++ )
if ( getRatioValid(x) >= cutoff )
sum++;
return sum;
}
public synchronized int[] getTotalNumValidResidues() throws Exception
{
return totalValid;
}
/** returns an alignment line id whose ungapped sequence is a perfect subfragment of the passed in sequence,
* if one exists.
*
* Otherwise returns null
*/
public AlignmentLine findPerfectSubframgent( String fragment ) throws Exception
{
fragment = fragment.toUpperCase();
StringBuffer queryBuff = new StringBuffer();
for ( int x=0; x< fragment.length(); x++ )
{
char c= fragment.charAt(x);
if ( MapResiduesToIndex.isValidResidueChar(c))
queryBuff.append(c);
}
fragment = queryBuff.toString();
for ( Iterator i = this.getAlignmentLines().iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
String theSequence = aLine.getUngappedSequence().toUpperCase();
if ( theSequence.indexOf(fragment) != -1 ||
fragment.indexOf(theSequence) != -1 )
return aLine;
}
return null;
}
/** The first token in the file should be an identifier
* The second token should be the sequence
*/
public static List getAlignmentLinesFromFile( File file, boolean forceToUpperCase ) throws Exception
{
List alignmentLines = new ArrayList();
BufferedReader reader = new BufferedReader( new FileReader( file ));
String nextLine = reader.readLine();
while ( nextLine != null && nextLine.trim().length() > 0 )
{
StringTokenizer sToken = new StringTokenizer( nextLine );
String id = sToken.nextToken();
String sequence = sToken.nextToken();
if ( forceToUpperCase )
sequence = sequence.toUpperCase();
alignmentLines.add( new AlignmentLine(id, sequence));
//System.out.println( sequence );
nextLine = reader.readLine();
}
return alignmentLines;
}
/** The first token in the file should be an identifier
* The second token should be the sequence
*/
public Alignment( String alignmentID,
File file,
boolean forceToUpperCase) throws Exception
{
this(alignmentID, getAlignmentLinesFromFile(file, forceToUpperCase ));
}
public Alignment( String alignmentID,
List<AlignmentLine> alignmentLines) throws Exception
{
this.alignmentID = alignmentID;
this.alignmentLines = Collections.unmodifiableList(alignmentLines);
this.numColumns = assertAllAlignmentsEqualLength();
this.columnStrings = new String[ this.numColumns];
for ( int x=0; x < this.numColumns; x++ )
{
StringBuffer buff = new StringBuffer();
for ( Iterator i = this.alignmentLines.iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
buff.append( aLine.getSequence().charAt(x));
}
columnStrings[x] = buff.toString();
}
this.counts = new int[ numColumns][ MapResiduesToIndex.NUM_VALID_RESIDUES];
for ( int x=0; x < numColumns; x++ )
{
for ( int y =0; y < alignmentLines.size(); y++ )
{
AlignmentLine aLine = (AlignmentLine) alignmentLines.get(y);
String sequence = aLine.getSequence();
// cycle through all 20 residues
for (int z=0; z < MapResiduesToIndex.NUM_VALID_RESIDUES; z++ )
{
if ( sequence.charAt(x) == MapResiduesToIndex.getChar(z) )
counts[x][z]++;
}
}
}
this.frequencies = new float[ MapResiduesToIndex.NUM_VALID_RESIDUES];
for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
this.frequencies[x] = 0;
for ( int y=0; y< MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
for ( int x=0; x< counts.length; x++ )
this.frequencies[y] += counts[x][y];
float totalNum = 0;
for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
totalNum += this.frequencies[x];
for ( int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
this.frequencies[x] /= totalNum;
totalValid = new int[ counts.length];
for ( int x=0; x < totalValid.length; x++ )
totalValid[x] = 0;
for (int x=0; x< counts.length; x++)
{
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
{
totalValid[x] += counts[x][y];
}
}
}
/** returns the length of all of the alignments
*/
private int assertAllAlignmentsEqualLength() throws Exception
{
if ( this.alignmentLines.size() == 0 )
return 0;
int aLength = ((AlignmentLine) this.alignmentLines.iterator().next()).getSequence().length();
for ( Iterator i = this.alignmentLines.iterator();
i.hasNext();
)
{
AlignmentLine aLine = (AlignmentLine) i.next();
//System.out.println(aLine.getIdentifier() + " " + aLine.getSequence() );
String sequence = aLine.getSequence();
if ( sequence.length() != aLength )
throw new Exception("Expecting a length of " + aLength + " but got a length of " +
sequence.length() );
}
return aLength;
}
/** The first index goes from 0 to i, representing columns in the multiple sequence alignment
* the second index goes from 0 to 19 representing types of Amino Acids.
* Use MapResiduesToIndex.getChar() to map from the numbers to single-letter amino acid codes
*/
public synchronized int[][] getCounts() throws Exception
{
return counts;
}
private String getFirstTwentyChars( String inString )
{
if ( inString.length() >= 20 )
return inString.substring( 0, 20 );
StringBuffer buff = new StringBuffer();
buff.append( inString );
while ( buff.length() < 20 )
buff.append( " " );
return buff.toString();
}
/** Returns a number between 0 and 1 indicating the fraction of residues that are valid in
* column i. (0 == none valid, 1 == all valid ).
*/
public float getRatioValid( int col) throws Exception
{
int[][] counts = getCounts();
int sum = 0;
for (int x=0; x < MapResiduesToIndex.NUM_VALID_RESIDUES; x++ )
sum+= counts[col][x];
return ((float) sum)/this.alignmentLines.size();
}
/** Returns an array that with 20 frequencies corresponding to the relative frequency of
* each residue in the MSA
*/
public synchronized float[] getFrequencies() throws Exception
{
return this.frequencies;
}
public void dumpSubsetOfColsAsHtml( File file, int column1Pos, char column1Char,
int column2Pos, char column2Char ) throws Exception
{
if ( column1Pos > column2Pos )
throw new Exception("Columns out of order");
BufferedWriter writer = new BufferedWriter( new FileWriter( file ));
writer.write("<html><body>");
writer.write("<pre>");
for ( int x=0; x<20; x++ )
writer.write("-");
writer.write( "" + ( column1Pos/ 100 ));
writer.write( "" + ( column2Pos/ 100 ));
writer.write( "\n");
for ( int x=0; x<20; x++ )
writer.write("-");
writer.write( "" + ( ( column1Pos - (column1Pos / 100) * 100 ) / 10));
writer.write( "" + ( ( column2Pos - (column2Pos / 100) * 100 ) / 10));
writer.write("\n");
for ( int x=0; x<20; x++ )
writer.write("-");
writer.write( "" + ( column1Pos - (column1Pos/10) * 10 ));
writer.write( "" + ( column2Pos - (column2Pos/10) * 10 ));
writer.write("\n\n");
for ( Iterator i=this.alignmentLines.iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
String aSequence = aLine.getSequence();
writer.write( getFirstTwentyChars( aLine.getIdentifier() ));
for ( int x=0; x< aSequence.length(); x++ )
{
if ( x == column1Pos || x == column2Pos )
{
boolean addColor =false;
if ( x == column1Pos && aSequence.charAt(x) == column1Char )
addColor = true;
if ( x == column2Pos && aSequence.charAt(x) == column2Char )
addColor = true;
if ( addColor )
writer.write("<font face==\"Courier\" color=red>");
writer.write( aSequence.charAt(x));
if ( addColor )
writer.write( "</font>");
}
}
writer.write( "\n");
}
writer.write("</pre></body></html>");
writer.flush(); writer.close();
}
/** only shows 10 residues on either side of pairs
*/
public void dumpSubsetAlignmentAsHTML( File file, List pairColors ) throws Exception
{
}
public void dumpUngappedAlignmentAsHtml( File file, List pairColors ) throws Exception
{
getCounts(); // initialzie counts
BufferedWriter writer = new BufferedWriter( new FileWriter( file ));
writer.write("<html><body>");
writer.write("<pre>");
dumpAlignmentHeaderWithStrippedGaps(writer);
for ( Iterator i=this.alignmentLines.iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
String aSequence = aLine.getSequence();
writer.write( getFirstTwentyChars( aLine.getIdentifier() ));
for ( int x=0; x< aSequence.length(); x++ )
{
if ( getRatioValid(x) > 0.5 )
{
boolean addColor =false;
boolean makeGrey = false;
if ( MapResiduesToIndex.isValidResidueChar(aSequence.charAt(x)) &&
100f * counts[x][MapResiduesToIndex.getIndex(aSequence.charAt(x))]
/ getNumSequencesInAlignment() >= 40f )
makeGrey = true;
String colorString = PairColors.getColorStringAsRange(pairColors, aLine, x );
if ( colorString != PairColors.DEFAULT_COLOR_STRING )
addColor = true;
if ( addColor || makeGrey )
writer.write( "<font ");
if ( addColor )
writer.write(" color= " + colorString + " " );
if ( makeGrey )
writer.write( " style=\"background:gray\" ");
if ( addColor || makeGrey )
writer.write( ">");
writer.write( aSequence.charAt(x));
if ( addColor || makeGrey)
writer.write( "</font>");
}
}
writer.write(" " + aLine.getIdentifier() );
writer.write( "\n");
}
writer.write("</pre></body></html>");
writer.flush(); writer.close();
}
public void dumpAlignmentAsHTML( File file, List pairColors ) throws Exception
{
getCounts(); // initialzie counts
BufferedWriter writer = new BufferedWriter( new FileWriter( file ));
writer.write("<html><body>");
writer.write("<pre>");
dumpAlignmentHeader(writer);
for ( Iterator i=this.alignmentLines.iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
String aSequence = aLine.getSequence();
writer.write( getFirstTwentyChars( aLine.getIdentifier() ));
for ( int x=0; x< aSequence.length(); x++ )
{
boolean addColor =false;
boolean makeGrey = false;
if ( MapResiduesToIndex.isValidResidueChar(aSequence.charAt(x)) &&
100f * counts[x][MapResiduesToIndex.getIndex(aSequence.charAt(x))]
/ getNumSequencesInAlignment() >= 40f )
makeGrey = true;
String colorString = PairColors.getColorString(pairColors, aLine, x );
if ( colorString != PairColors.DEFAULT_COLOR_STRING )
addColor = true;
if ( addColor || makeGrey )
writer.write( "<font ");
if ( addColor )
writer.write(" color= " + colorString + " " );
if ( makeGrey )
writer.write( " style=\"background:gray\" ");
if ( addColor || makeGrey )
writer.write( ">");
writer.write( aSequence.charAt(x));
if ( addColor || makeGrey)
writer.write( "</font>");
}
writer.write( "\n");
}
writer.write("</pre></body></html>");
writer.flush(); writer.close();
}
public void dumpAlignmentHeader( BufferedWriter writer ) throws Exception
{
for ( int x=0; x<20; x++ )
writer.write("-");
for ( int x=1; x<=getNumColumnsInAlignment(); x++ )
writer.write( "" + ( x / 100 ));
writer.write( "\n");
for ( int x=0; x<20; x++ )
writer.write("-");
for ( int x=1; x<=getNumColumnsInAlignment(); x++ )
writer.write( "" + ( ( x - (x / 100) * 100 ) / 10));
writer.write("\n");
for ( int x=0; x<20; x++ )
writer.write("-");
for ( int x=1; x<=getNumColumnsInAlignment(); x++ )
{
writer.write( "" + ( x - (x/10) * 10 ));
}
writer.write("\n\n");
}
private void dumpAlignmentHeaderWithStrippedGaps( BufferedWriter writer ) throws Exception
{
for ( int x=0; x<20; x++ )
writer.write("-");
for ( int x=1; x<=getNumColumnsInAlignment(); x++ )
if ( getRatioValid(x-1) > 0.5 )
writer.write( "" + ( x / 100 ));
writer.write( "\n");
for ( int x=0; x<20; x++ )
writer.write("-");
for ( int x=1; x<=getNumColumnsInAlignment(); x++ )
if ( getRatioValid(x-1) > 0.5 )
writer.write( "" + ( ( x - (x / 100) * 100 ) / 10));
writer.write("\n");
for ( int x=0; x<20; x++ )
writer.write("-");
for ( int x=1; x<=getNumColumnsInAlignment(); x++ )
if ( getRatioValid(x-1) > 0.5 )
writer.write( "" + ( x - (x/10) * 10 ));
writer.write("\n\n");
}
public void dumpAlignmnetWithHeader( File file ) throws Exception
{
BufferedWriter writer = new BufferedWriter( new FileWriter( file ));
dumpAlignmentHeader(writer);
dumpAlignment(writer);
writer.flush(); writer.close();
}
public void dumpAlignmentAsFasta( File file ) throws Exception
{
BufferedWriter writer = new BufferedWriter( new FileWriter( file ));
for ( Iterator i = alignmentLines.iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
writer.write( ">" + aLine.getIdentifier() + "\n" );
writer.write( aLine.getSequence() + "\n" );
}
writer.flush(); writer.close();
}
public void dumpAlignment( File file ) throws Exception
{
BufferedWriter writer = new BufferedWriter( new FileWriter( file ));
dumpAlignment(writer);
writer.flush(); writer.close();
}
public void dumpAlignment( BufferedWriter writer ) throws Exception
{
for ( Iterator i=this.alignmentLines.iterator();
i.hasNext(); )
{
AlignmentLine aLine = (AlignmentLine) i.next();
writer.write( getFirstTwentyChars( aLine.getIdentifier() ));
writer.write( aLine.getSequence() );
writer.write( "\n");
}
writer.flush();
}
public synchronized PFamPdbAnnotationParser[] getAnnotationParsers()
{
return pdbIds;
}
public synchronized PFamPdbAnnotationParser getAPdbIdParser(String pdbId, char chain)
{
for ( int x=0; x< this.pdbIds.length; x++ )
{
if ( pdbIds[x].getChainChar() == chain &&
pdbIds[x].getFourCharId().equals(pdbId) )
return pdbIds[x];
}
return null;
}
private synchronized void setPdbIds( PFamPdbAnnotationParser[] newPdbIDs )
{
this.pdbIds = newPdbIDs;
}
public synchronized void setPdbIds(List pdbStringList) throws Exception
{
this.pdbIds = new PFamPdbAnnotationParser[ pdbStringList.size() ];
int num = 0;
for ( Iterator i = pdbStringList.iterator();
i.hasNext(); )
{
pdbIds[num] = new PFamPdbAnnotationParser( i.next().toString() );
num++;
}
}
public synchronized PFamPdbAnnotationParser[] getPdbIds()
{
return pdbIds;
}
public static char[] getMostFrequentResidues(Alignment anAlignment) throws Exception
{
char[] residues = new char[ anAlignment.getNumColumnsInAlignment() ];
int[][] counts = anAlignment.getCounts();
for ( int x=0; x< anAlignment.getNumColumnsInAlignment(); x++ )
{
long max = 0;
residues[x] = '-';
for ( int y=0; y < MapResiduesToIndex.NUM_VALID_RESIDUES; y++ )
{
if ( counts[x][y] > max )
{
max = counts[x][y];
residues[x] = MapResiduesToIndex.getChar( y );
}
}
}
return residues;
}
@Override
public String toString() {
return "Alignment [alignmentID=" + alignmentID + ", numColumns="
+ numColumns + ", pdbIds=" + Arrays.toString(pdbIds) + "]";
}
}
| 27,536 | 24.66356 | 110 | java |
cobs | cobs-master/cobs/covariance/datacontainers/SequenceFeature.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
public class SequenceFeature
{
private int startInclusive;
private int endInclusive;
private String color;
int sequenceNum;
public SequenceFeature( int start, int end, String color, int sequenceNum )
{
this.startInclusive = start;
this.endInclusive = end;
this.color = color;
this.sequenceNum = sequenceNum;
}
public String getColor()
{
return color;
}
public int getEndInclusive()
{
return endInclusive;
}
public int getStartInclusive()
{
return startInclusive;
}
public int getSequenceNum()
{
return sequenceNum;
}
}
| 1,242 | 22.018519 | 77 | java |
cobs | cobs-master/cobs/covariance/datacontainers/AlignmentSubScore.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class AlignmentSubScore
{
private char xChar;
private char yChar;
private int numObserved;
private float numExpected;
private float score;
public static AlignmentSubScore getASubScore( Collection subScores, char xChar, char yChar )
{
for ( Iterator i = subScores.iterator();
i.hasNext(); )
{
AlignmentSubScore aSubScore = (AlignmentSubScore) i.next();
if ( aSubScore.getXChar() == xChar && aSubScore.getYChar() == yChar )
return aSubScore;
}
return null;
}
public AlignmentSubScore( char xChar, char yChar, int numObserved,
float numExpected, float score )
{
this.xChar = xChar;
this.yChar = yChar;
this.numObserved = numObserved;
this.numExpected = numExpected;
this.score = score;
}
public float getNumExpected()
{
return numExpected;
}
public int getNumObserved()
{
return numObserved;
}
public float getScore()
{
return score;
}
public char getXChar()
{
return xChar;
}
public char getYChar()
{
return yChar;
}
public static String getHeader()
{
return "xChar\tyChar\tnumObserved\tnumExpected\tscore\tPositveCovariance\n";
}
public String getTabbedLine()
{
StringBuffer buff = new StringBuffer();
buff.append( this.xChar + "\t" );
buff.append( this.yChar + "\t" );
buff.append( this.numObserved + "\t" );
buff.append( this.numExpected + "\t" );
buff.append( this.score + "\t");
if ( this.numObserved > this.numExpected )
buff.append( "positive\n" );
else if ( this.numExpected > this.numObserved )
buff.append( "negative\n" );
else
buff.append("equal\n");
return buff.toString();
}
public static void writeToFile ( File file, List subScores ) throws Exception
{
BufferedWriter writer = new BufferedWriter( new FileWriter( file ));
writer.write( getHeader() );
for ( int x=0; x < subScores.size(); x++ )
{
AlignmentSubScore aSubScore = (AlignmentSubScore ) subScores.get(x);
writer.write( aSubScore.getTabbedLine() );
}
writer.flush(); writer.close();
}
}
| 2,896 | 22.362903 | 94 | java |
cobs | cobs-master/cobs/covariance/datacontainers/ClustalLine.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.datacontainers;
public class ClustalLine
{
private int positionInOriginatingSequence;
private int clustalIndex;
private boolean isAlignmentSequence;
private String lineName;
public ClustalLine(
String lineName,
int clustalIndex,
int positionInOriginatingSequence,
boolean isAlignmentSequence )
{
this.lineName = lineName;
this.clustalIndex = clustalIndex;
this.positionInOriginatingSequence = positionInOriginatingSequence;
this.isAlignmentSequence = isAlignmentSequence;
}
public int getClustalIndex()
{
return clustalIndex;
}
public boolean isAlignmentSequence()
{
return isAlignmentSequence;
}
public String getLineName()
{
return lineName;
}
public int getPositionInOriginatingSequence()
{
return positionInOriginatingSequence;
}
public void incrementPositionInOriginalSequence()
{
this.positionInOriginatingSequence++;
}
}
| 1,573 | 24.387097 | 74 | java |
cobs | cobs-master/cobs/covariance/parsers/PdbParser.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.parsers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import utils.SequenceUtils;
import covariance.datacontainers.PdbAtom;
import covariance.datacontainers.PdbChain;
import covariance.datacontainers.PdbFileWrapper;
import covariance.datacontainers.PdbResidue;
public class PdbParser
{
private int numResidues = -1;
public PdbParser(String filePathToParse, PdbFileWrapper pdbWrapper ) throws Exception
{
File fileToParse = new File(filePathToParse);
if ( ! fileToParse.exists() )
throw new Exception("Error! Could not find " + fileToParse.getAbsolutePath() );
List atomsList = readAtoms( fileToParse );
populateWrapper(atomsList, pdbWrapper);
pdbWrapper.setPdbId(getFourCharId(fileToParse).toLowerCase());
pdbWrapper.setExperimentMethod(getExpData(fileToParse));
}
String getExpData( File fileToParse ) throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader( fileToParse ));
String nextLine = reader.readLine();
while ( nextLine != null && nextLine.trim().length() > 0 )
{
if ( nextLine.startsWith("EXPDTA") )
{
StringTokenizer sToken = new StringTokenizer( nextLine );
sToken.nextToken();
return sToken.nextToken();
}
nextLine = reader.readLine();
}
reader.close();
return null;
}
private String getFourCharId( File fileToParse ) throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader( fileToParse ));
String firstLine = reader.readLine();
reader.close();
return firstLine.substring(62,66);
}
private List readAtoms( File fileToParse ) throws Exception
{
List list = new ArrayList();
BufferedReader reader = new BufferedReader( new FileReader( fileToParse));
String nextLine = reader.readLine();
while ( nextLine != null )
{
if ( nextLine.startsWith("ATOM"))
{
PdbAtom atom = new PdbAtom( nextLine );
list.add( atom );
}
nextLine = reader.readLine();
}
reader.close();
return list;
}
/** Todo: Implement more efficiently
*/
private HashSet getChainChars(List atomList)
{
HashSet chainChars = new HashSet();
for (Iterator i = atomList.iterator();
i.hasNext(); )
{
PdbAtom atom = (PdbAtom) i.next();
chainChars.add( new Character( atom.getChainId() ));
}
return chainChars;
}
/** Todo: Implement more efficiently
*/
private HashSet getResiduesInts(List atomList)
{
HashSet residueInts = new HashSet();
for ( Iterator i = atomList.iterator();
i.hasNext(); )
{
PdbAtom pdbAtom = (PdbAtom) i.next();
residueInts.add( new Integer( pdbAtom.getResidueSequenceNumber() ));
}
return residueInts;
}
private void populateWrapper( List atomList, PdbFileWrapper pdbWrapper ) throws Exception
{
Collection chainChars = getChainChars(atomList);
for ( Iterator i = chainChars.iterator();
i.hasNext(); )
{
char chainChar = ((Character) i.next()).charValue();
PdbChain pdbChain = new PdbChain(chainChar, pdbWrapper);
populateResidues(atomList, pdbChain);
pdbWrapper.addChain(pdbChain);
}
}
private void populateResidues( List atomsList, PdbChain pdbChain ) throws Exception
{
Collection residueInts = getResiduesInts( atomsList);
for ( Iterator i = residueInts.iterator();
i.hasNext(); )
{
int residueInt = (( Integer ) i.next()).intValue();
List subList = getAtomsInResidue(atomsList, pdbChain.getChainChar(), residueInt);
if ( subList.size() > 0 )
{
char residueChar = getResidueCharFromList(subList);
PdbResidue pdbResidue = new PdbResidue(residueChar, residueInt, pdbChain);
pdbChain.addResidue(pdbResidue);
for ( Iterator i2 = subList.iterator();
i2.hasNext(); )
{
PdbAtom atom = (PdbAtom) i2.next();
if ( pdbResidue.getAtom(atom.getAtomName()) == null )
{
pdbResidue.addPdbAtom(atom);
}
else
{
//System.out.println("Warning! Already have " +
// atom.getResidueSequenceNumber() + " " + atom.getAtomName() );
}
}
}
}
}
private char getResidueCharFromList( List subList ) throws Exception
{
String residueName = ((PdbAtom) subList.get(0)).getResidueName();
for ( Iterator i = subList.iterator();
i.hasNext(); )
{
PdbAtom atom = (PdbAtom) i.next();
//if ( ! atom.getResidueName().equals(residueName) )
//System.out.println("Warning. Unequal residue names " +
// atom.getResidueName() + " vs " + residueName );
}
return SequenceUtils.threeToOne(residueName).charAt(0);
}
/** Todo: This is probably too slow
*/
private List getAtomsInResidue( List atomsList,
char chainChar,
int residueInt ) throws Exception
{
List list = new ArrayList();
for ( Iterator i = atomsList.iterator();
i.hasNext(); )
{
PdbAtom atom = (PdbAtom) i.next();
if ( atom.getResidueSequenceNumber() == residueInt
&& atom.getChainId() == chainChar )
list.add( atom );
}
return list;
}
}
| 5,965 | 24.279661 | 90 | java |
cobs | cobs-master/cobs/covariance/parsers/HitScores.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.parsers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.zip.GZIPInputStream;
import utils.OrderedSequenceRange;
import utils.TabReader;
/*
* Holds the results of blastall output with -m 8
*/
public class HitScores implements Comparable<HitScores>
{
//# Fields: Query id, Subject id, % identity, alignment length, mismatches, gap op
//enings, q. start, q. end, s. start, s. end, e-value, bit score
private String queryId;
private final String targetId;
private final float percentIdentity;
private final int alignmentLength;
private final int numMismatches;
private final int gapOpenings;
private final int queryStart;
private final int queryEnd;
private final int targetStart;
private final int targetEnd;
private final double eScore;
private final float bitScore;
//Queryid Subjectid percentIdentity alignmentlength mismatches gap_openings querystart queryend targetstart targetEnd evalue bitScore
public static class PercentIdentitySorter implements Comparator<HitScores>
{
public int compare(HitScores o1, HitScores o2)
{
return Float.compare(o2.percentIdentity, o1.percentIdentity);
}
}
public void setQueryId(String queryId)
{
this.queryId = queryId;
}
/*
* The file line is the result of a blast run with the blast output set to 8
* //# Fields: Query id, Subject id, % identity, alignment length, mismatches, gap op
//enings, q. start, q. end, s. start, s. end, e-value, bit score
*/
public HitScores(String fileLine) throws Exception
{
TabReader sToken = new TabReader(fileLine);
this.queryId = sToken.nextToken();
this.targetId = sToken.nextToken();
this.percentIdentity = Float.parseFloat(sToken.nextToken());
this.alignmentLength = Integer.parseInt(sToken.nextToken());
this.numMismatches = Integer.parseInt(sToken.nextToken());
this.gapOpenings = Integer.parseInt(sToken.nextToken());
this.queryStart = Integer.parseInt(sToken.nextToken());
this.queryEnd = Integer.parseInt(sToken.nextToken());
this.targetStart = Integer.parseInt(sToken.nextToken());
this.targetEnd = Integer.parseInt( sToken.nextToken());
this.eScore = Double.parseDouble(sToken.nextToken());
this.bitScore = Float.parseFloat(sToken.nextToken());
if( sToken.hasMore())
throw new Exception("Parsing error");
}
public OrderedSequenceRange getTargetRange()
{
return new OrderedSequenceRange(this.targetStart, this.targetEnd);
}
public OrderedSequenceRange getQueryRange()
{
return new OrderedSequenceRange(this.queryStart, this.queryEnd);
}
/*
* Returns the gi identifier the gi identifier ( e.g. 119668705 )
*/
public String getTargetGenbankId()
{
String returnString = getTargetId();
returnString = returnString.substring(3);
returnString = returnString.substring(0, returnString.indexOf("|"));
return returnString;
}
public static HashSet<String> getAllGenbankIdsForCollection( Collection<HitScores> c )
{
HashSet<String> set = new HashSet<String>();
for( HitScores hs : c )
set.add(hs.getTargetGenbankId());
return set;
}
/*
* Throws if there any duplicate queryIDs in the results file
*/
public static HashMap<String, HitScores> getUniqueQueryIDMap(File fileToParse)
throws Exception
{
BufferedReader reader = new BufferedReader(new FileReader(fileToParse));
HashMap<String, HitScores> map = new HashMap<String, HitScores>();
reader.readLine();
String nextLine = reader.readLine();
while(nextLine != null)
{
if( ! nextLine.startsWith("#"))
{
HitScores hs = new HitScores(nextLine);
if( map.get(hs.getQueryId()) != null )
throw new Exception("Error! Duplicate keys for " + hs.getQueryId());
map.put(hs.getQueryId(), hs);
}
nextLine = reader.readLine();
}
reader.close();
return map;
}
/*
* Writes the top hit for each query to the file defined by
* FilePathGenerator.getTopHitsFile().
*/
public static void writeToFile( Collection<HitScores> scores, File file, boolean writeHeader)
throws Exception
{
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
if( writeHeader)
writeHeader(writer, true);
for( HitScores hs : scores )
hs.writeALine(writer, true);
writer.flush(); writer.close();
}
public static HashSet<HitScores> filter(Collection<HitScores> scores,
double eScore, double length) throws Exception
{
HashSet<HitScores> returnSet = new HashSet<HitScores>();
for( HitScores hs : scores )
if( hs.getEScore() <= eScore && hs.getQueryAlignmentLength() >= length)
returnSet.add(hs);
return returnSet;
}
public static HashMap<String,HitScores> getTopHitsFilteredByPercentIdentityAtMinLength(
String filepath, int minLength) throws Exception
{
//Query id, Subject id, % identity, alignment length
HashMap<String, HitScores> map= new HashMap<String, HitScores>();
BufferedReader reader = new BufferedReader(new FileReader(filepath));
String nextLine = reader.readLine();
int index=0;
while( nextLine != null)
{
String[] splits = nextLine.split("\t");
if( splits.length != 12)
throw new Exception("Parsing error");
HitScores hs = new HitScores(nextLine);
HitScores oldHit= map.get(hs.getQueryId());
if( hs.getAlignmentLength() >= minLength)
{
if(oldHit== null || hs.getPercentIdentity() > oldHit.getPercentIdentity() )
{
map.put(hs.getQueryId(), hs);
}
}
nextLine= reader.readLine();
if( index % 100000==0)
System.out.println(index + " " + map.size());
index++;
}
reader.close();
return map;
}
public static HashMap<String, HitScores> getTopHitsAsQueryMap(String filepath) throws Exception
{
HashMap<String, HitScores> map= new LinkedHashMap<String, HitScores>();
BufferedReader reader = new BufferedReader(new FileReader(filepath));
String nextLine = reader.readLine();
int index=0;
while( nextLine != null)
{
HitScores hs = new HitScores(nextLine);
HitScores oldHit = map.get(hs.getQueryId());
if( oldHit == null || hs.getBitScore()> oldHit.getBitScore())
map.put(hs.getQueryId(), hs);
nextLine= reader.readLine();
if( index % 100000==0)
System.out.println(index + " " + map.size());
index++;
}
reader.close();
return map;
}
public static List<HitScores> getTopHits(String filepath) throws Exception
{
return new ArrayList<HitScores>(getTopHitsAsQueryMap(filepath).values());
}
public static List<HitScores> getTopHits(List<HitScores> inHits) throws Exception
{
HashMap<String, HitScores> map= new LinkedHashMap<String, HitScores>();
List<HitScores> returnList= new ArrayList<HitScores>();
for( HitScores hs : inHits)
{
HitScores oldScore = map.get(hs.getQueryId());
if( oldScore == null || hs.getEScore() < oldScore.getEScore())
map.put(hs.getQueryId(), hs);
}
for( String s : map.keySet() )
returnList.add(map.get(s));
return returnList;
}
public static HashSet<String> getUniqueQueryIds( Collection<HitScores> collection )
{
HashSet<String> returnSet = new HashSet<String>();
for( HitScores hs : collection)
returnSet.add(hs.getQueryId());
return returnSet;
}
public static void writeHeader(BufferedWriter writer, boolean endWithNewline ) throws Exception
{
writer.write("queryId\t");
writer.write("targetId\tpercentIdentity\t");
writer.write("alignmentLength\tmismatches\t");
writer.write("gapOpenings\tqueryStart\tqueryEnd\t");
writer.write("targetStart\ttargetEnd\teValue\tbitScore");
writer.write( endWithNewline ? "\n" : "\t" );
}
public void writeALine( BufferedWriter writer, boolean endWithNewline) throws Exception
{
writer.write(queryId + "\t");
writer.write(targetId + "\t");
writer.write(percentIdentity + "\t");
writer.write(alignmentLength + "\t");
writer.write(numMismatches + "\t");
writer.write(gapOpenings + "\t");
writer.write(queryStart + "\t");
writer.write(queryEnd + "\t");
writer.write(targetStart + "\t");
writer.write(targetEnd + "\t");
writer.write(eScore + "\t");
writer.write("" + bitScore);
writer.write( endWithNewline ? "\n" : "\t" );
}
public static HashSet<String> getQueryIds(File file, double cutoffEScore, int cutoffSequenceLength)
throws Exception
{
HashSet<String> queryIds = new HashSet<String>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String nextLine = reader.readLine();
while( nextLine != null )
{
if( ! nextLine.startsWith("#"))
{
HitScores hs = new HitScores(nextLine);
if( hs.getEScore() <= cutoffEScore )
if( Math.abs(hs.getTargetEnd()-hs.getTargetStart()) <= cutoffSequenceLength )
{
String id = hs.getQueryId();
id = id.substring( id.lastIndexOf("|") + 1, id.length() );
queryIds.add(id);
//System.out.println(hs.getQueryId() + " " + id);
}
}
nextLine = reader.readLine();
}
return queryIds;
}
public static List<HitScores> getAsList( String filepath) throws Exception
{
return getAsList(new File(filepath), false);
}
public static List<HitScores> getAsList( File file, boolean gzipped) throws Exception
{
System.out.println("PARSING: " + file.getAbsolutePath());
BufferedReader reader =
gzipped ?
new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( file) ) ))
:
new BufferedReader(new FileReader(file));
List<HitScores> list = new ArrayList<HitScores>();
String nextLine = reader.readLine();
// empty file
if( nextLine == null )
return list;
if(nextLine.startsWith("queryId"))
nextLine = reader.readLine();
while( nextLine != null )
{
if( ! nextLine.startsWith("#"))
{
list.add(new HitScores(nextLine));
}
nextLine = reader.readLine();
}
if( nextLine != null)
throw new Exception("Parsing error");
return list;
}
public static HashSet<String> getKeysForCutoff(HashMap<String,HitScores> map,
double maxEScore, int minAlignmentLength)
{
HashSet<String> returnSet = new HashSet<String>();
for( HitScores hs : map.values() )
if( hs.getEScore() <= maxEScore && hs.getQueryAlignmentLength() >= minAlignmentLength)
returnSet.add(hs.getQueryId());
return returnSet;
}
public static List<HitScores> getAsList(File file, double maxEScore, int minAlignmentLength)
throws Exception
{
BufferedReader reader = new BufferedReader(new FileReader(file));
List<HitScores> list = new ArrayList<HitScores>();
String nextLine = reader.readLine();
while( nextLine != null )
{
if( ! nextLine.startsWith("#"))
{
HitScores hs = new HitScores(nextLine);
if( hs.getEScore() <= maxEScore && hs.getQueryAlignmentLength() >= minAlignmentLength )
list.add(hs);
}
nextLine = reader.readLine();
}
return list;
}
public int getNumMismatches()
{
return numMismatches;
}
public float getPercentIdentity()
{
return percentIdentity;
}
public double getEScore()
{
return eScore;
}
public String getTargetId()
{
return targetId;
}
public int compareTo(HitScores other)
{
return Double.compare(this.eScore, other.eScore);
}
public String getQueryId()
{
return queryId;
}
public int getQueryEnd()
{
return queryEnd;
}
public int getQueryStart()
{
return queryStart;
}
public int getTargetEnd()
{
return targetEnd;
}
public int getTargetStart()
{
return targetStart;
}
public int getAlignmentLength()
{
return alignmentLength;
}
public int getQueryAlignmentLength()
{
return Math.abs(queryEnd - queryStart);
}
public float getBitScore()
{
return bitScore;
}
public int getGapOpenings()
{
return gapOpenings;
}
public static void main(String[] args) throws Exception
{
}
}
| 12,960 | 23.877159 | 134 | java |
cobs | cobs-master/cobs/covariance/parsers/PFamPdbAnnotationParser.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.parsers;
import java.util.StringTokenizer;
public class PFamPdbAnnotationParser
{
private String id;
private char chainChar;
private int startPos;
private int endPos;
private String pdbAnnotationString;
private int length;
public PFamPdbAnnotationParser( String pdbAnnotationString) throws Exception
{
this.pdbAnnotationString= pdbAnnotationString;
StringTokenizer sToken = new StringTokenizer( pdbAnnotationString);
if ( ! sToken.nextToken().equals("#=GF"))
throw new Exception("Error! Expecting " + "#=GF" );
if ( ! sToken.nextToken().equals("DR"))
throw new Exception("Error! Expecting " + "DR" );
if ( ! sToken.nextToken().equals("PDB;"))
throw new Exception("Error! Expecting " + "PDB;" );
id = sToken.nextToken();
if ( id.length() != 4 )
throw new Exception("Expecting a pdb id for " + id );
String chainString = sToken.nextToken();
if ( chainString.equals(";" ))
{
chainChar = ' ';
}
else
{
if ( ! chainString.endsWith(";") || chainString.length() != 2 )
throw new Exception("Error! Expecting a chain X; for " + chainString);
chainChar = chainString.charAt(0);
}
String startString = sToken.nextToken();
if ( ! startString.endsWith(";") )
throw new Exception("Error! Expecting a terminating semi-colon for " + startString );
startPos = Integer.parseInt( startString.substring( 0, startString.length()-1 ));
String endString = sToken.nextToken();
if ( ! endString.endsWith(";" ) )
throw new Exception("Error! Expecting a terminating semi-colon for " + endString );
endPos = Integer.parseInt( endString.substring( 0, endString.length()-1 ));
this.length = endPos - startPos;
if ( length < 0 )
throw new Exception("Error! Negative length for " + endPos + " " + startPos );
}
/** The four char pdb id plus the chain is used for equals() and hashCode()
*/
public boolean equals(Object obj)
{
return this.pdbAnnotationString.equals(((PFamPdbAnnotationParser)obj).pdbAnnotationString);
}
/** The four char pdb id plus the chain is used for equals() and hashCode()
*/
public int hashCode()
{
return this.pdbAnnotationString.hashCode();
}
public int getEndPos()
{
return endPos;
}
public String getFourCharId()
{
return id;
}
public int getLength()
{
return length;
}
public String getPdbAnnotationString()
{
return pdbAnnotationString;
}
public int getStartPos()
{
return startPos;
}
public char getChainChar()
{
return chainChar;
}
public String toString()
{
return this.id + " " + this.chainChar + " " + startPos + " " + endPos;
}
} | 3,340 | 24.120301 | 93 | java |
cobs | cobs-master/cobs/covariance/parsers/PfamToPDBBlastResults.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.parsers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import utils.ConfigReader;
public class PfamToPDBBlastResults
{
//pdbId chainID pfamID pfamLine pfamStart pfamEnd pdbStart pdbEnd percentIdentity
//pdbLength eScore numberOfElements elements
private final String pdbID;
private final char chainId;
private final String pfamID;
private final String pfamLine;
private final int pfamStart;
private final int pfamEnd;
private final int pdbStart;
private final int pdbEnd;
private double percentIdentity;
private final int pdbLength;
private final double eScore;
private final int numberOfElements;
private final String elements;
private final String originalLine;
public String getOriginalLine()
{
return originalLine;
}
public String getPdbID()
{
return pdbID;
}
public char getChainId()
{
return chainId;
}
public String getPfamLine()
{
return pfamLine;
}
public int getPfamStart()
{
return pfamStart;
}
public int getPfamEnd()
{
return pfamEnd;
}
public int getPdbStart()
{
return pdbStart;
}
public int getPdbEnd()
{
return pdbEnd;
}
public double getPercentIdentity()
{
return percentIdentity;
}
public int getPdbLength()
{
return pdbLength;
}
public double geteScore()
{
return eScore;
}
public int getNumberOfElements()
{
return numberOfElements;
}
public String getElements()
{
return elements;
}
public String getPfamID()
{
return pfamID;
}
private PfamToPDBBlastResults(String s) throws Exception
{
StringTokenizer sToken = new StringTokenizer(s, "\t");
this.pdbID = sToken.nextToken();
this.chainId= sToken.nextToken().charAt(0);
this.pfamID = sToken.nextToken();
this.pfamLine = sToken.nextToken();
this.pfamStart = Integer.parseInt(sToken.nextToken());
this.pfamEnd = Integer.parseInt(sToken.nextToken());
this.pdbStart = Integer.parseInt(sToken.nextToken());
this.pdbEnd = Integer.parseInt(sToken.nextToken());
this.percentIdentity = Double.parseDouble(sToken.nextToken());
this.pdbLength = Integer.parseInt(sToken.nextToken());
this.eScore = Double.parseDouble(sToken.nextToken());
this.numberOfElements = Integer.parseInt(sToken.nextToken());
this.elements = sToken.nextToken();
this.originalLine=s;
if(sToken.hasMoreTokens())
throw new Exception("Unexpected token " + sToken.nextToken());
}
public static HashMap<String, PfamToPDBBlastResults> getAsMap() throws Exception
{
HashMap<String, PfamToPDBBlastResults> map = new LinkedHashMap<String, PfamToPDBBlastResults>();
File file = new File(ConfigReader.getPdbPfamChain());
BufferedReader reader =
file.getName().toLowerCase().endsWith("gz") ?
new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( file )))) :
new BufferedReader(new FileReader(file)) ;
reader.readLine();
for(String s = reader.readLine(); s != null; s= reader.readLine())
{
PfamToPDBBlastResults results = new PfamToPDBBlastResults(s);
if( map.containsKey(results.getPfamID()))
throw new Exception("Duplicate pfam id " + results.getPfamID());
map.put(results.getPfamID(), results);
}
reader.close();
return map;
}
@Override
public String toString() {
java.lang.reflect.Field[] fields = getClass().getDeclaredFields();
AccessibleObject.setAccessible(fields,true);
StringBuffer sb = new StringBuffer();
sb.append("Class: " + this.getClass().getName() + "\n");
for (java.lang.reflect.Field field : fields) {
Object value = null;
try {
value = field.get(this);
} catch (IllegalAccessException e) {continue;}
sb.append("\tField \"" + field.getName() + "\"\n");
Class fieldType = field.getType();
sb.append("\t\tType: ");
if (fieldType.isArray()) {
Class subType = fieldType.getComponentType();
int length = Array.getLength(value);
sb.append(subType.getName() + "[" + length + "]" + "\n");
for (int i = 0; i < length; i ++) {
Object obj = Array.get(value,i);
sb.append("\t\tValue " + i + ": " + obj + "\n");
}
} else {
sb.append(fieldType.getName() + "\n");
sb.append("\t\tValue: ");
sb.append((value == null) ? "NULL" : value.toString());
sb.append("\n");
}
}
return sb.toString();
}
public static void main(String[] args) throws Exception
{
HashMap<String, PfamToPDBBlastResults> map = getAsMap();
for(PfamToPDBBlastResults toPDB : map.values())
System.out.println(toPDB.toString());
}
}
| 5,664 | 24.633484 | 99 | java |
cobs | cobs-master/cobs/covariance/parsers/PfamParser.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.parsers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import utils.ConfigReader;
import utils.SequenceUtils;
import covariance.datacontainers.Alignment;
import covariance.datacontainers.AlignmentLine;
public class PfamParser
{
private String lastLineRead = null;
private boolean finished = false;
private BufferedReader pFamReader;
private int numLinesRead=0;
public boolean isFinished()
{
return finished;
}
public PfamParser() throws Exception
{
this(ConfigReader.getFullPfamPath().toLowerCase().endsWith("gz"));
}
public PfamParser(boolean zipped) throws Exception
{
pFamReader = zipped ? new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( ConfigReader.getFullPfamPath()) ) ),100000)
: new BufferedReader( new FileReader( new File( ConfigReader.getFullPfamPath())),100000);
}
private AlignmentLine getAlignmentLine() throws Exception
{
//System.out.println("Got initial line of " + lastLineRead );
StringTokenizer sToken = new StringTokenizer(lastLineRead);
AlignmentLine aLine = new AlignmentLine(
new StringTokenizer(sToken.nextToken(), "/").nextToken(),
sToken.nextToken() );
if( sToken.hasMoreTokens())
throw new Exception("Parsing error ");
return aLine;
}
public Alignment getAnAlignment(String pfamId) throws Exception
{
for(Alignment a = getNextAlignment(); a != null; a = getNextAlignment())
{
System.out.println(a.getAligmentID());
if( a.getAligmentID().equals(pfamId))
return a;
}
throw new Exception("Could not find ");
}
/** gets the next alignment from the reader.
*
* The cursor in the reader should be set to a line that starts with "# STOCKHOLM 1.0"
* or this will throw.
*
* Returns null when there are no more alignments to read ( after which isFinished() will return true)
*/
public Alignment getNextAlignment() throws Exception
{
List pdbIds = new ArrayList();
lastLineRead = getNextLine();
if ( lastLineRead == null )
return null;
if ( ! lastLineRead.trim().equals("# STOCKHOLM 1.0") )
throw new Exception("Error! First line should be # STOCKHOLM 1.0 at "+ numLinesRead );
lastLineRead = getNextLine();
// files produced by WriteTruncatedPfamAlignments may end here..
if( lastLineRead == null)
{
finished = true;
return null;
}
if ( ! lastLineRead.startsWith("#=GF ID" ))
throw new Exception("Error! Second line should start #=GF ID at "+ numLinesRead );
int index = lastLineRead.indexOf("#=GF ID" );
if ( index == -1 )
throw new Exception("Logic error");
String id = lastLineRead.substring(7).trim();
while ( lastLineRead.startsWith("#"))
{
StringTokenizer sToken = new StringTokenizer(lastLineRead);
if ( sToken.nextToken().equals("#=GF") &&
sToken.nextToken().equals("DR") &&
sToken.nextToken().startsWith("PDB") )
pdbIds.add( lastLineRead );
lastLineRead = getNextLine();
}
List alignmentLines = new ArrayList();
while ( lastLineRead != null && ! lastLineRead.trim().equals("//") )
{
if ( ! lastLineRead.startsWith("#" ))
alignmentLines.add( getAlignmentLine() );
lastLineRead = getNextLine();
}
Alignment a = new Alignment( id, alignmentLines );
SequenceUtils.trimPdbIDs(pdbIds);
a.setPdbIds( pdbIds);
return a;
}
private String getNextLine() throws Exception
{
if ( finished )
throw new Exception("Error! Nothing left to read");
numLinesRead++;
String nextLine = pFamReader.readLine();
if ( nextLine == null || nextLine.trim().length() == 0 )
finished = true;
//System.out.println("Reading " + nextLine );
return nextLine;
}
}
| 4,602 | 26.39881 | 105 | java |
cobs | cobs-master/cobs/covariance/parsers/FastaSequence.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package covariance.parsers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.StringTokenizer;
public class FastaSequence implements Comparable<FastaSequence>
{
public static final String BLAST_SUFFIX = "_BLAST";
private String header;
private StringBuffer sequence = new StringBuffer();
public boolean equals(Object obj)
{
FastaSequence o = (FastaSequence) obj;
if( ! o.getHeader().equals(getHeader()))
return false;
if( ! o.getSequence().equals(getSequence()))
return false;
return true;
}
public String getHeader()
{
return header;
}
public FastaSequence( String header, String sequence ) throws Exception
{
if ( ! header.startsWith(">") )
header = ">" + header;
this.header = header;
this.sequence = new StringBuffer( sequence);
}
public static HashMap<String, FastaSequence> getFirstTokenSequenceMap(String filePath)
throws Exception
{
return getFirstTokenSequenceMap(new File(filePath));
}
public static HashMap<String, FastaSequence> getFirstTokenSequenceMap(File file)
throws Exception
{
List<FastaSequence> list = readFastaFile( file);
HashMap<String, FastaSequence> map = new LinkedHashMap<String, FastaSequence>();
for( FastaSequence fs : list)
{
String key = new StringTokenizer(fs.getHeader()).nextToken();
if( key.startsWith(">"))
key = key.substring(1);
if( map.containsKey(key) )
throw new Exception("Duplicate key " + key);
map.put(key, fs);
}
return map;
}
public String getSecondTokenOfHeader()
{
StringTokenizer sToken = new StringTokenizer(header);
sToken.nextToken();
String s = sToken.nextToken();
return s;
}
public String getFirstTokenOfHeader()
{
StringTokenizer sToken = new StringTokenizer(header);
String s = sToken.nextToken();
if( s.startsWith(">"))
s = s.substring(1);
return s;
}
public static String stripWhiteSpace( String inString ) throws Exception
{
StringBuffer buff = new StringBuffer();
for ( int x=0; x< inString.length(); x++ )
{
char c = inString.charAt(x);
if ( ! Character.isWhitespace(c) )
buff.append(c);
}
return buff.toString();
}
public FastaSequence()
{
}
public String getSequence()
{
return sequence.toString();
}
/*
* Does not hold the entire fileToParse in RAM, so this is good for large FASTA files.
* Will return only the FastaSequences in matchingFirstToken whose header matches
* something in that set (not including the ">")
*/
public static List<FastaSequence> getOnlyMatching( File fileToParse,
HashSet<String> matchingFirstTokens) throws Exception
{
List<FastaSequence> returnList = new ArrayList<FastaSequence>();
BufferedReader reader = new BufferedReader( new FileReader(
fileToParse));
String nextLine = reader.readLine();
while ( nextLine != null )
{
String originalHeader = nextLine;
String header = originalHeader;
if( ! header.startsWith(">"))
throw new Exception("Parsing error " + header);
header = new StringTokenizer(header).nextToken();
header = header.substring(1);
nextLine = reader.readLine();
StringBuffer buff = new StringBuffer();
while ( nextLine != null && ! nextLine.startsWith(">") )
{
buff.append( FastaSequence.stripWhiteSpace( nextLine ) );
nextLine = reader.readLine();
}
if( matchingFirstTokens.contains(header))
{
returnList.add(new FastaSequence(originalHeader,
buff.toString()));
}
}
return returnList;
}
public static String getFasta( FastaSequence seq1, FastaSequence seq2 ) throws Exception
{
StringBuffer buff = new StringBuffer();
buff.append(seq1.header + "\n");
buff.append(seq1.sequence + "\n");
buff.append(seq2.header + "\n" );
buff.append(seq2.sequence + "\n" );
return buff.toString();
}
public static FastaSequence getFirstSequence(String filePath) throws Exception
{
return getFirstSequence(new File(filePath));
}
public static FastaSequence getFirstSequence(File file) throws Exception
{
return (FastaSequence) readFastaFile(file).get(0);
}
public static List<FastaSequence> readFastaFile(String filePath) throws Exception
{
return readFastaFile(new File(filePath));
}
public static HashMap<String, String> getHeaderFirstTokenMap(String filepath) throws Exception
{
return getHeaderFirstTokenMap(new File(filepath));
}
public static HashMap<String, String> getHeaderFirstTokenMap(File file) throws Exception
{
HashMap<String, String> returnMap = new HashMap<String,String>();
BufferedReader reader = new BufferedReader( new FileReader(
file));
String nextLine = reader.readLine();
while ( nextLine != null )
{
String originalHeader = nextLine;
String header = originalHeader;
header = new StringTokenizer(header).nextToken();
if( header.startsWith(">"))
header = header.substring(1);
if( returnMap.containsKey(header))
throw new Exception("Error! Duplicate header");
returnMap.put(header, originalHeader);
//System.out.println(header);
nextLine = reader.readLine();
while ( nextLine != null && ! nextLine.startsWith(">") )
{
nextLine = reader.readLine();
}
}
return returnMap;
}
public static HashMap<String, Integer> getCountMap(List<File> fastaFiles) throws Exception
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
for( File f : fastaFiles)
{
BufferedReader reader = new BufferedReader(new FileReader(f));
String nextLine = reader.readLine();
while ( nextLine != null )
{
String header = nextLine;
header = new StringTokenizer(header).nextToken();
if( header.startsWith(">"))
header = header.substring(1);
if( map.keySet().contains(header) )
throw new Exception("Duplicate key " + header);
nextLine = reader.readLine();
int count = 0;
while ( nextLine != null && ! nextLine.startsWith(">") )
{
count+= stripWhiteSpace( nextLine ).length();
nextLine = reader.readLine();
}
map.put(header, count);
}
reader.close();
}
return map;
}
public static List<FastaSequence> readFastaFile( File file) throws Exception
{
return readFastaFile(file, -1);
}
public static List<FastaSequence> readFastaFile( File file, int limit ) throws Exception
{
List<FastaSequence> list = new ArrayList<FastaSequence>();
BufferedReader reader = new BufferedReader( new FileReader( file ));
String nextLine = reader.readLine();
//consume blank lines at the top of the file
while( nextLine != null && nextLine.trim().length() == 0 )
nextLine= reader.readLine();
while ( nextLine != null )
{
if( limit != -1 && list.size() >= limit)
{
reader.close();
return list;
}
FastaSequence fs = new FastaSequence();
list.add(fs);
fs.header = nextLine;
nextLine = reader.readLine();
while ( nextLine != null && ! nextLine.startsWith(">") )
{
fs.sequence.append( stripWhiteSpace( nextLine ) );
nextLine = reader.readLine();
}
//consume blanks that might occur after the ">"
while( nextLine != null && nextLine.trim().length() == 0 )
nextLine= reader.readLine();
}
// There appears to be some kind of bug between the BufferedReader and
// Linux that, amazingly, seems to sometimes cause this Exception to fire!
// the two lines of code above that consume blank lines prevent this Exception.
// this, however,makes no sense to me and is, I think, some kind of subtle
// threading bug in BufferedReader.readLine(..) that I haven't had the time to track down...
// with this line, we simply fail the parser if this bug ever rears its head again..
if( nextLine != null)
throw new Exception("Logic exception. Parsing failed");
reader.close();
return list;
}
public static List<FastaSequence> readFastaFileForceToUpper( File file ) throws Exception
{
List<FastaSequence> list = new ArrayList<FastaSequence>();
BufferedReader reader = new BufferedReader( new FileReader( file ));
String nextLine = reader.readLine();
while ( nextLine != null )
{
FastaSequence fs = new FastaSequence();
list.add(fs);
fs.header = nextLine;
nextLine = reader.readLine();
while ( nextLine != null && ! nextLine.startsWith(">") )
{
fs.sequence.append( stripWhiteSpace( nextLine ).toUpperCase() );
nextLine = reader.readLine();
}
}
return list;
}
/*
* Does not check for membership in set of { A,C,G,T}
*
* Returns the number of {G,C} over all other characters.
*/
public float getGCRatio() throws Exception
{
float numGC = 0;
String testString = this.getSequence().toUpperCase();
for( int x=0; x < testString.length(); x++ )
{
char c = testString.charAt(x);
if( c=='C' || c=='G' )
numGC++;
}
return numGC / testString.length();
}
public float getRatioValidForDNA() throws Exception
{
float numValid = 0;
String testString = this.getSequence().toUpperCase();
for( int x=0; x < testString.length(); x++ )
{
char c = testString.charAt(x);
if( c== 'A' || c=='C' || c=='G' || c=='T' )
numValid++;
}
return numValid / testString.length();
}
public void writeFastaFile(File file) throws Exception
{
BufferedWriter writer = new BufferedWriter( new FileWriter( file ));
writer.write(this.header + "\n");
writer.write(this.sequence + "\n");
writer.flush(); writer.close();
}
/** Sort by length
*/
public int compareTo(FastaSequence otherFasta)
{
if ( this.sequence.length() > otherFasta.sequence.length() )
return -1;
if ( this.sequence.length() < otherFasta.sequence.length() )
return 1;
return 0;
}
}
| 10,806 | 23.34009 | 95 | java |
cobs | cobs-master/cobs/preparePfamToPDBBlast/ExaminePDBs.java |
/**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package preparePfamToPDBBlast;
import gocAlgorithms.HelixSheetGroup;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import utils.ConfigReader;
public class ExaminePDBs
{
/*
* First run parsers.PfamToPDB.main()
*
* This will require at least 7 elements
*
*/
public static void main(String[] args) throws Exception
{
HashMap<String, PfamToPDB> map = PfamToPDB.getMapByName();
BufferedWriter writer= new BufferedWriter(new FileWriter("c:\\temp\\newLinesFiltered.txt"));
writer.write("PDB_ID\tCHAIN_ID\tpfamID\tnumberOfElements\telements\n");
int numDone=0;
for(PfamToPDB pfamToPdb : map.values())
{
try
{
File pdbFile = new File(ConfigReader.getPdbDir() + File.separator + pfamToPdb.getPdbID() + ".txt");
List<HelixSheetGroup> list= HelixSheetGroup.getList(pdbFile.getAbsolutePath(), pfamToPdb.getChainID(), pfamToPdb.getPdbResidueStart(),
pfamToPdb.getPdbResidueEnd());
//System.out.println(list.size() + " " + pfamToPdb.getPdbID());
if(list.size() >=7)
{
numDone++;
writer.write( pfamToPdb.getPdbID() + "\t" + pfamToPdb.getChainID() + "\t" +
pfamToPdb.getPfamName() + "\t" + list.size() + "\t" + list + "\n");
System.out.println( numDone + " " + pfamToPdb.getPdbID() );
writer.flush();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
writer.flush(); writer.close();
}
}
| 2,130 | 28.597222 | 139 | java |
cobs | cobs-master/cobs/preparePfamToPDBBlast/BlastPDBToPfam.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package preparePfamToPDBBlast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Random;
import utils.ConfigReader;
import utils.ProcessWrapper;
import covariance.datacontainers.Alignment;
import covariance.datacontainers.PdbFileWrapper;
import covariance.parsers.HitScores;
import covariance.parsers.PfamParser;
/*
* First run scratch.ExaminePDBs
*/
public class BlastPDBToPfam
{
private static Random random = new Random();
public static void main(String[] args) throws Exception
{
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("c:\\temp\\newLineWithBlast.txt")));
writer.write("pdbId\tchainID\tpfamID\tpfamLine\tpfamStart\tpfamEnd\tqueryStart\tqueryEnd\tpercentIdentity\tpdbLength\teScore\tnumberOfElements\telements\n");
HashMap<String, PfamToPbdWithHelicesAndSheets> blastMap = PfamToPbdWithHelicesAndSheets.getAsMap();
PfamParser parser = new PfamParser();
for( Alignment a = parser.getNextAlignment(); a != null; a = parser.getNextAlignment())
{
PfamToPbdWithHelicesAndSheets blastResults = blastMap.get(a.getAligmentID());
if(blastResults != null)
{
try
{
File databaseFile = new File("c:\\temp\\temp" + File.separator + a.getAligmentID());
a.writeUngappedAsFasta(databaseFile.getAbsolutePath());
System.out.println(a.getAligmentID());
makeBlastDB(databaseFile);
PdbFileWrapper wrapper = new PdbFileWrapper(blastResults.getPdbID());
HitScores hs = getTopHit(blastResults, wrapper, databaseFile);
writer.write( blastResults.getPdbID() + "\t" + blastResults.getChainId() + "\t" +
blastResults.getPfamID() + "\t" + hs.getTargetId() + "\t" +
hs.getTargetStart() + "\t" + hs.getTargetEnd() + "\t" +
hs.getQueryStart() + "\t" + hs.getQueryEnd() + "\t" +
hs.getPercentIdentity() + "\t" + (hs.getQueryEnd() -hs.getQueryStart())
+ "\t" + hs.getEScore() + "\t" + blastResults.getNumberOfElements() + "\t" +
blastResults.getElements() + "\n");
writer.flush();
System.out.println("Wrote " + a.getAligmentID());
}
catch(Exception ex)
{
// the pdb files can sometimes throw.
ex.printStackTrace();
}
}
}
writer.flush(); writer.close();
}
private static HitScores getTopHit(PfamToPbdWithHelicesAndSheets blastResults, PdbFileWrapper wrapper, File databaseFile) throws Exception
{
File outFile = new File(ConfigReader.getBlastDir() + File.separator + "PfamTEMP.txt" + "_" + System.currentTimeMillis() +
random.nextLong()
);
outFile.delete();
if(outFile.exists())
throw new Exception("out File exists");
File queryFile = new File(ConfigReader.getBlastDir() + File.separator + "queryFileTEMP.txt");
queryFile.delete();
if( queryFile.exists())
throw new Exception("query File exits");
String seq = wrapper.getChain(blastResults.getChainId()).getSequence();
BufferedWriter writer = new BufferedWriter(new FileWriter(queryFile));
writer.write(">" + blastResults.getPdbID() + "\n");
writer.write(seq + "\n");
writer.flush(); writer.close();
String[] args = new String[11];
args[0] = ConfigReader.getBlastDir() + File.separator + "blastall";
args[1] = "-p";
args[2] ="blastp";
args[3] = "-d";
args[4] = databaseFile.getAbsolutePath();
args[5] = "-o";
args[6] = outFile.getAbsolutePath();
args[7] = "-i";
args[8] = queryFile.getAbsolutePath();
args[9] = "-m";
args[10] = "8";
new ProcessWrapper(args);
HitScores hitScore = HitScores.getTopHits(outFile.getAbsolutePath()).get(0);
outFile.delete();
return hitScore;
}
private static void makeBlastDB(File inFile) throws Exception
{
String[] args = new String[5];
args[0] = ConfigReader.getBlastDir() + File.separator + "formatdb";
args[1] = "-p";
args[2] = "t";
args[3] = "-i";
args[4] = inFile.getAbsolutePath();
new ProcessWrapper(args);
}
}
| 4,665 | 29.900662 | 159 | java |
cobs | cobs-master/cobs/preparePfamToPDBBlast/WriteElementsBasedOnCurrentPdbCoordinates.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package preparePfamToPDBBlast;
import gocAlgorithms.HelixSheetGroup;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import utils.ConfigReader;
import covariance.parsers.PfamToPDBBlastResults;
/**
*
* To be run after ExamineAlignments
*/
public class WriteElementsBasedOnCurrentPdbCoordinates
{
public static void main(String[] args) throws Exception
{
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(
"c:\\temp\\pdbPfamFile3.txt" )));
writer.write("pdbId\tchainID\tpfamID\tpfamLine\tpfamStart\tpfamEnd\tpdbStart\t" + "" +
"pdbEnd\tpercentIdentity\tpdbLength\teScore\tnumberOfElements\telements\n");
HashMap<String, PfamToPDBBlastResults> map = PfamToPDBBlastResults.getAsMap();
for(PfamToPDBBlastResults toPDB: map.values())
{
System.out.println(toPDB.getPfamID());
List<HelixSheetGroup> helixSheetGroup=
HelixSheetGroup.getList(ConfigReader.getPdbDir() + File.separator + toPDB.getPdbID() + ".txt",
toPDB.getChainId(), toPDB.getPdbStart(), toPDB.getPdbEnd());
writer.write( toPDB.getPdbID() + "\t" );
writer.write( toPDB.getChainId() + "\t");
writer.write( toPDB.getPfamID() + "\t");
writer.write( toPDB.getPfamLine() + "\t");
writer.write( toPDB.getPfamStart() + "\t");
writer.write( toPDB.getPfamEnd() + "\t");
writer.write( toPDB.getPdbStart() + "\t");
writer.write( toPDB.getPdbEnd() + "\t");
writer.write( toPDB.getPercentIdentity() + "\t");
writer.write( (toPDB.getPdbEnd() - toPDB.getPdbStart()) + "\t");
writer.write( toPDB.geteScore() + "\t" );
writer.write( helixSheetGroup.size() + "\t");
writer.write( helixSheetGroup+ "\n");
}
writer.flush(); writer.close();
}
}
| 2,431 | 33.253521 | 99 | java |
cobs | cobs-master/cobs/preparePfamToPDBBlast/ExamineAlignments.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package preparePfamToPDBBlast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import cobsScripts.WriteScores;
import covariance.datacontainers.Alignment;
import covariance.datacontainers.PdbFileWrapper;
import covariance.parsers.PfamParser;
import covariance.parsers.PfamToPDBBlastResults;
public class ExamineAlignments
{
/*
* Run scratch.SecondFilterOfPfamIDs.
*
* If the global alignment comes out overly gapped, we take out the last few alignments
*/
public static void main(String[] args) throws Exception
{
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(
"c:\\temp\\pdbToPfamForCobsViaBlast2.txt")));
writer.write("pdbId\tchainID\tpfamID\tpfamLine\tpfamStart\tpfamEnd\t" + "" +
"pdbStart\tpdbEnd\tpercentIdentity\tpdbLength\teScore\tnumberOfElements\telements\n");
PfamParser parser = new PfamParser();
HashMap<String, PfamToPDBBlastResults> map = PfamToPDBBlastResults.getAsMap();
int numFailures=0;
int numSuccesses =0;
while( ! parser.isFinished())
{
Alignment a = parser.getNextAlignment();
if(a.getNumSequencesInAlignment() <200 || a.getNumSequencesInAlignment() > 2000)
throw new Exception("Unexpected number of sequences ");
PfamToPDBBlastResults toPdb = map.get(a.getAligmentID());
if( toPdb!= null)
{
String pdbInQuestion = toPdb.getPdbID();
PdbFileWrapper fileWrapper = new PdbFileWrapper(pdbInQuestion);
try
{
WriteScores.getPdbToAlignmentNumberMap(a, toPdb, fileWrapper);
numSuccesses++;
writer.write(toPdb.getOriginalLine() + "\n");
writer.flush();
}
catch(Exception ex)
{
ex.printStackTrace();
System.err.println("We seemed to have an issue parsing for a particular PDB on this family, skipping");
System.exit(1);
numFailures++;
}
System.out.println("SUCCESS " + numSuccesses + " FAILURE " + numFailures);
}
}
writer.flush(); writer.close();
}
}
| 2,665 | 30 | 108 | java |
cobs | cobs-master/cobs/preparePfamToPDBBlast/PfamToPbdWithHelicesAndSheets.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package preparePfamToPDBBlast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.StringTokenizer;
/*
* First run parsers.PfamToPDB.main()
* then scratch.ExaminePDBs
* then scratch.BlastPDBToPfam
*/
class PfamToPbdWithHelicesAndSheets
{
private String pdbID;
private char chainId;
private String pfamID;
private int numberOfElements;
private String elements;
public String getPdbID()
{
return pdbID;
}
public void setPdbID(String pdbID)
{
this.pdbID = pdbID;
}
public char getChainId()
{
return chainId;
}
public void setChainId(char chainId)
{
this.chainId = chainId;
}
public String getPfamID()
{
return pfamID;
}
public void setPfamID(String pfamID)
{
this.pfamID = pfamID;
}
public int getNumberOfElements()
{
return numberOfElements;
}
public void setNumberOfElements(int numberOfElements)
{
this.numberOfElements = numberOfElements;
}
public String getElements()
{
return elements;
}
public void setElements(String elements)
{
this.elements = elements;
}
private PfamToPbdWithHelicesAndSheets(String s) throws Exception
{
StringTokenizer sToken = new StringTokenizer(s, "\t");
this.pdbID = sToken.nextToken();
this.chainId = sToken.nextToken().charAt(0);
this.pfamID = sToken.nextToken();
this.numberOfElements = Integer.parseInt(sToken.nextToken());
this.elements = sToken.nextToken();
if( sToken.hasMoreTokens())
throw new Exception("Unexpeced token " + sToken.nextToken());
}
public static HashMap<String, PfamToPbdWithHelicesAndSheets> getAsMap() throws Exception
{
BufferedReader reader = new BufferedReader(new FileReader(new File("c:\\temp\\newLinesFiltered.txt")));
reader.readLine();
HashMap<String, PfamToPbdWithHelicesAndSheets> map = new HashMap<String, PfamToPbdWithHelicesAndSheets>();
for( String s= reader.readLine(); s!= null; s= reader.readLine())
{
PfamToPbdWithHelicesAndSheets blastResults = new PfamToPbdWithHelicesAndSheets(s);
if( map.containsKey(blastResults.getPfamID()))
throw new Exception("Duplicate id");
map.put(blastResults.getPfamID(), blastResults);
}
reader.close();
return map;
}
}
| 2,897 | 22.184 | 108 | java |
cobs | cobs-master/cobs/preparePfamToPDBBlast/PfamToPDB.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package preparePfamToPDBBlast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.zip.GZIPInputStream;
import cobsScripts.WriteScores;
import covariance.datacontainers.Alignment;
import covariance.parsers.PfamParser;
import utils.ConfigReader;
class PfamToPDB
{
private String pdbID;
private char chainID;
private int pdbResidueStart;
private int pdbResidueEnd;
private String pfamAccession;
private String pfamName;
private String pfamBestHit;
private double eValue;
private String originalLine;
public String getOriginalLine()
{
return originalLine;
}
public void setPfamBestHit(String pfamBestHit)
{
this.pfamBestHit = pfamBestHit;
}
public double getEValue()
{
return eValue;
}
public String getPfamBestHit()
{
return pfamBestHit;
}
public String getPdbID()
{
return pdbID;
}
public char getChainID()
{
return chainID;
}
public int getPdbResidueStart()
{
return pdbResidueStart;
}
public int getPdbResidueEnd()
{
return pdbResidueEnd;
}
public String getPfamAccession()
{
return pfamAccession;
}
public String getPfamName()
{
return pfamName;
}
public static HashMap<String, PfamToPDB> getMapByName() throws Exception
{
HashMap<String, PfamToPDB> map = new LinkedHashMap<String, PfamToPDB>();
File file = new File(ConfigReader.getPdbPfamChain());
BufferedReader reader = file.getName().toLowerCase().endsWith("gz") ?
new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( file )))) :
new BufferedReader(new FileReader(file)) ;
reader.readLine();
for(String s = reader.readLine();
s != null;
s = reader.readLine())
{
//System.out.println(s);
String[] splits = s.split("\t");
PfamToPDB pdb = new PfamToPDB();
pdb.pdbID = new String(splits[0]);
String chainString = splits[1];
if( chainString.length() != 1)
throw new Exception("Parsing error");
pdb.chainID = chainString.charAt(0);
pdb.originalLine = s;
pdb.pdbResidueStart = Integer.parseInt( splits[2].replaceAll("[A-Z]", ""));
pdb.pdbResidueEnd = Integer.parseInt(splits[3].replaceAll("[A-Z]", ""));
if( pdb.pdbResidueEnd < pdb.pdbResidueStart)
{
int temp = pdb.pdbResidueEnd;
pdb.pdbResidueEnd = pdb.pdbResidueStart;
pdb.pdbResidueStart = temp;
}
pdb.pfamAccession = new String(splits[4]);
pdb.pfamName = new String(splits[5]);
pdb.eValue = Double.parseDouble(splits[7]);
if( splits.length != 8)
throw new Exception("Unexpected token " + s);
PfamToPDB oldPdb = map.get(pdb.pfamName);
if( pdb.pdbID.length() == 4 && ( oldPdb == null || pdb.eValue < oldPdb.eValue))
map.put(pdb.pfamName, pdb);
}
reader.close();
return map;
}
public static void main(String[] args) throws Exception
{
BufferedWriter writer = new BufferedWriter(new FileWriter("c:\\temp\\newLines.txt"));
HashMap<String, PfamToPDB> map = PfamToPDB.getMapByName();
System.out.println(map.size());
System.out.println(map.containsKey("1-cysPrx_C"));
PfamParser parser = new PfamParser();
while( ! parser.isFinished())
{
Alignment a = parser.getNextAlignment();
PfamToPDB aPDB = map.get(a.getAligmentID());
if( aPDB != null && a.getNumSequencesInAlignment() >= 200 && a.getNumSequencesInAlignment() <= 2000 &&
aPDB.pdbResidueEnd - aPDB.pdbResidueStart >= WriteScores.MIN_PDB_LENGTH )
{
System.out.println(a.getAligmentID());
writer.write( aPDB.originalLine + "\n" );
writer.flush();
}
}
writer.flush(); writer.close();
}
}
| 4,479 | 23.480874 | 105 | java |
cobs | cobs-master/cobs/utils/MapResiduesToIndex.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
import java.util.*;
public class MapResiduesToIndex
{
public static Random random = new Random(System.currentTimeMillis());
public static final char[] residues = new char[] { 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T',
'V', 'W', 'Y' };
public static final HashMap<Character,Integer> residueHashMap = new HashMap<Character,Integer>(){
{
put('A', 0);
put('C', 1);
put('D', 2);
put('E', 3);
put('F', 4);
put('G', 5);
put('H', 6);
put('I', 7);
put('K', 8);
put('L', 9);
put('M', 10);
put('N', 11);
put('P', 12);
put('Q', 13);
put('R', 14);
put('S', 15);
put('T', 16);
put('V', 17);
put('W', 18);
put('Y', 19);
}
};
public static int NUM_VALID_RESIDUES = residues.length;
public static final Character[] charResidues = new Character[]
{
new Character('A'),
new Character('C'),
new Character('D'),
new Character('E'),
new Character('F'),
new Character('G'),
new Character('H'),
new Character('I'),
new Character('K'),
new Character('L'),
new Character('M'),
new Character('N'),
new Character('P'),
new Character('Q'),
new Character('R'),
new Character('S'),
new Character('T'),
new Character('V'),
new Character('W'),
new Character('Y')
};
public static char getChar( int i ) throws Exception
{
return residues[i];
}
public static char getRandomChar() throws Exception
{
return residues[ random.nextInt( residues.length ) ];
}
public static char getRandomCharFromDistribution(float[] distribution ) throws Exception
{
if ( distribution.length != MapResiduesToIndex.NUM_VALID_RESIDUES )
throw new Exception("Unexpected length");
float sum = 0f;
float randomFloat = random.nextFloat();
for ( int x=0; x< distribution.length; x++)
{
sum+= distribution[x];
if ( randomFloat <= sum )
return residues[x];
}
return residues[MapResiduesToIndex.NUM_VALID_RESIDUES -1];
}
public static Character getChararcter( int i ) throws Exception
{
return charResidues[i];
}
public static int getIndex(char c) throws Exception
{
for (int x=0; x<residues.length; x++ )
if ( residues[x] == c )
return x;
throw new Exception("Unknown character " + c );
}
public static int getIndexOrNegativeOne(char c) throws Exception
{
Character query = c;
query = Character.toUpperCase(query);
Integer answer = null;
answer = residueHashMap.get(query);
if (query=='-' || query=='.'){
return -1;
}
if (answer == null ){
//System.out.print("We did not find the amino acid code in question: " + query + " \n");
}
else{
return answer;
}
return -1;
}
public static int getIndex(String c) throws Exception
{
if ( c.length() != 1)
throw new Exception("Error! Expecting a length of one");
for (int x=0; x<residues.length; x++ )
if ( residues[x] == c.charAt(0) )
return x;
throw new Exception("Unknown character " + c );
}
public static boolean isValidResidueChar( char c )
{
for (int x=0; x<residues.length; x++ )
if ( residues[x] == c )
return true;
return false;
}
public static boolean isVaildThreeResidueString( String aString )
{
try
{
SequenceUtils.threeToOne(aString);
}
catch(Exception e )
{
return false;
}
return true;
}
}
| 4,291 | 23.11236 | 136 | java |
cobs | cobs-master/cobs/utils/ProcessWrapper.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProcessWrapper
{
public ProcessWrapper( String[] cmdArgs ) throws Exception
{
Runtime r = Runtime.getRuntime();
Process p = r.exec(cmdArgs);
for(String s : cmdArgs)
System.out.print(s + " ");
System.out.println();
BufferedReader br = new BufferedReader (new InputStreamReader(p.getInputStream ()));
String s;
while ((s = br.readLine ())!= null)
{
//System.out.println (s);
}
p.waitFor();
p.destroy();
br.close();
}
}
| 1,212 | 24.808511 | 86 | java |
cobs | cobs-master/cobs/utils/OrderedSequenceRange.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
public class OrderedSequenceRange
{
private final int startPosition;
private final int endPosition;
private boolean originallyForward;
/** if startSequence > endSequence, they will be switched
*/
public OrderedSequenceRange( int startPositionIn, int endPositionIn )
{
if ( startPositionIn > endPositionIn )
{
int temp = startPositionIn;
startPositionIn = endPositionIn;
endPositionIn = temp;
originallyForward = false;
}
else
{
originallyForward = true;
}
this.startPosition = startPositionIn;
this.endPosition = endPositionIn;
}
public boolean isInRange(int pos)
{
if ( pos >= startPosition && pos <= endPosition)
return true;
return false;
}
public int getEndPosition()
{
return endPosition;
}
public int getStartPosition()
{
return startPosition;
}
public String toString()
{
return "Start: " + this.startPosition + " End: " + this.endPosition;
}
public boolean isOriginallyForward()
{
return originallyForward;
}
public int getLength()
{
return this.endPosition - this.startPosition;
}
public int getOverlap(OrderedSequenceRange otherRange)
{
return Math.min(this.endPosition, otherRange.endPosition) -
Math.max(this.startPosition, otherRange.startPosition);
}
public static void main(String[] args)
{
OrderedSequenceRange osr = new OrderedSequenceRange(1,100);
System.out.println( osr.getOverlap(new OrderedSequenceRange(50,150)) );
}
}
| 2,119 | 22.820225 | 74 | java |
cobs | cobs-master/cobs/utils/TabReader.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
public class TabReader
{
private String inString;
public TabReader(String inString )
{
if ( inString == null )
throw new NullPointerException();
this.inString = inString;
}
public String nextToken()
{
return getNext();
}
public String getNext()
{
if ( inString == null )
throw new RuntimeException("Error! No more to get");
int index = inString.indexOf('\t');
String returnString = "";
if ( index == -1 )
{
returnString = inString;
inString = null;
}
else if ( index == 0 )
{
if ( inString.length() > 1 )
inString = inString.substring(1);
else
inString = "";
}
else
{
// there's a tab, but not at the first position
returnString = inString.substring(0, index );
inString = inString.substring( index );
if ( inString.length() <= 1 )
inString = "";
else
inString = inString.substring(1);
}
return returnString;
}
public boolean hasMore()
{
return this.inString != null;
}
}
| 1,979 | 25.4 | 74 | java |
cobs | cobs-master/cobs/utils/Avevar.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** Calculates mean and variance from an array of doubles
*/
public class Avevar
{
double ave;
double var;
public double getAve()
{
return ave;
}
public double getVar()
{
return var;
}
public double getSqrt()
{
return Math.sqrt(var);
}
public double getSD()
{
return Math.sqrt(var);
}
@Override
public String toString()
{
return this.getAve() + " " + this.getSD();
}
public Avevar( double[] data )
{
double s, ep;
int j;
ave = 0.0;
for ( j=0; j < data.length; j++ ) ave += data[j];
ave /= data.length;
var = ep = 00;
for ( j = 0; j < data.length; j++) {
s = data[j] - ave;
ep += s;
var += s*s;
}
var = ( var - ep * ep / data.length ) / ( data.length - 1);
}
public Avevar( List<? extends Number> data )
{
double s, ep;
int j;
ave = 0.0;
for ( j=0; j < data.size(); j++ ) ave += (data.get(j)).doubleValue();
ave /= data.size();
var = ep = 00;
for ( j = 0; j < data.size(); j++) {
s = (data.get(j)).doubleValue() - ave;
ep += s;
var += s*s;
}
var = ( var - ep * ep / data.size() ) / ( data.size()- 1);
}
public Avevar( float[] data )
{
double s, ep;
int j;
ave = 0.0;
for ( j=0; j < data.length; j++ ) ave += data[j];
ave /= data.length;
var = ep = 00;
for ( j = 0; j < data.length; j++) {
s = data[j] - ave;
ep += s;
var += s*s;
}
var = ( var - ep * ep / data.length ) / ( data.length - 1);
}
public static double getMedian(List<Double> list)
{
List<Double> newList = new ArrayList<Double>();
for(Double d : list)
newList.add(d);
Collections.sort(newList);
if( list.size() % 2== 1)
{
return newList.get(newList.size()/2);
}
return ( newList.get(newList.size()/2) + newList.get(newList.size()/2 -1))/2 ;
}
} | 2,575 | 18.664122 | 80 | java |
cobs | cobs-master/cobs/utils/TTest.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
import java.util.ArrayList;
import java.util.List;
public class TTest
{
/** Static methods only
*/
private TTest()
{
}
public static double getAverage( List list ) throws Exception
{
int count =0;
double sum =0;
for ( int x=0; x< list.size(); x++ )
{
count++;
sum += ((Double)list.get(x)).doubleValue();
}
return sum / count;
}
public static double getStDev( List data ) throws Exception
{
int j;
double ep=0.0,s,p;
s =0.0;
int n=data.size();
if (n <= 1) throw new Exception("n must be at least 2 in moment");
for (j=0;j<n;j++) s += ((Double)data.get(j)).doubleValue();
double ave=s/n;
double adev=0.0;
double var=0.0;;
for (j=0;j<n;j++) {
s=((Double)data.get(j)).doubleValue()-ave;
ep += s;
var += (p=s*s);
}
adev /= n;
var=(var-ep*ep/n)/(n-1);
return Math.sqrt(var);
}
public static double lnfactorial(double number)
{
return(gammln(number+1));
}
public static double gammln( double xx )
{
int j;
double x, y, tmp, ser;
double[] cof = {
76.18009172947146,
-86.50532032941677,
24.01409824083091,
-1.231739572450155,
0.1208650973866179e-2,
-0.539523938495e-5
};
y=x=xx;
tmp=x+5.5;
tmp -= (x+0.5)*Math.log(tmp);
ser=1.000000000190015;
for ( j=0;j<6;j++) ser += cof[j]/++y;
return -tmp+Math.log(2.5066282746310005*ser/x);
}
public static double betai( double a, double b, double x )
{
double bt;
if ( x < 0.0 || x > 1.0 )
throw new RuntimeException("x " + x + " out of bound");
if ( x == 0 || x == 1.0 )
bt = 0.0;
else
bt = Math.exp( gammln( a+b ) - gammln(a) - gammln(b)
+ a * Math.log( x ) + b * Math.log( 1.0 - x ));
if ( x < (a + 1.0) / (a+b+2.0))
return bt * betacf(a,b,x)/a;
else
return 1.0 - bt * betacf( b,a, 1.0 -x) / b;
}
public static double betacf( double a, double b, double x )
{
int MAXIT=100;
double EPS = getEpsilon();
double FPMIN = Double.MIN_VALUE / EPS;
int m, m2;
double aa, c, d, del, h, qab, qam, qap;
qab = a+b;
qap = a + 1.0;
qam = a - 1.0;
c=1.0;
d=1.0-qab*x/qap;
if ( Math.abs(d) < FPMIN ) d=FPMIN;
d = 1.0/d;
h=d;
for( m=1;m<=MAXIT;m++) {
m2 = 2*m;
aa = m*(b-m)*x / ((qam+m2)*(a+m2));
d = 1.0 + aa * d;
if ( Math.abs(d) < FPMIN ) d = FPMIN;
c= 1.0 + aa / c;
if ( Math.abs(c) < FPMIN) c = FPMIN;
d= 1.0 / d;
h *= d * c;
aa = -(a+m) * (qab + m ) * x / ((a+m2) * ( qap + m2));
d=1.0 + aa * d;
if ( Math.abs(d) < FPMIN) d = FPMIN;
c = 1.0 + aa / c;
if ( Math.abs(c) < FPMIN) c= FPMIN;
d=1.0/d;
del=d*c;
h *= del;
if ( Math.abs( del - 1.0 ) <= EPS ) break;
}
if ( m > MAXIT )
throw new RuntimeException("a or b too big, of MAXIT too small");
return h;
}
/** This method returns the difference between 1 and the smallest value
* greater than 1 that is representable for double
*/
public static double getEpsilon()
{
long oneLong = Double.doubleToLongBits( 1.0 );
long oneLongPlus = oneLong | Double.doubleToLongBits( Double.MIN_VALUE );
double dblPlus = Double.longBitsToDouble( oneLongPlus );
double dblOne = Double.longBitsToDouble( oneLong );
return dblPlus - dblOne;
}
public static void main(String[] args)
throws Exception
{
/*
double[] d1 = { 4,3,5,6,7,5,3,4,5,6,6 };
double[] d2 = { 2,3,4,4,5,4,2,1,3,4,5 };
System.out.println( ttest( d1, d2 ));
for ( int x=0; x< 100; x++ )
System.out.println( x + "! " + gammln(x+1) + " " + Math.log( Factorials.getFactorial(x+1).doubleValue()) );
*/
List list = new ArrayList();
list.add( new Double(4));
list.add( new Double(5));
list.add( new Double(6));
list.add( new Double(3));
list.add( new Double(2));
list.add( new Double(1));
list.add( new Double(4.3));
list.add( new Double(2.1));
System.out.println( getStDev(list));
}
private static void printBinary( long l )
{
for(int i = 63; i >=0; i--)
if(((1L << i) & l) != 0)
System.out.print("1");
else
System.out.print("0");
System.out.println();
}
public static double ttest(double[] data1, double[] data2)
{
double t;
double prob;
double var1, var2, svar, df, ave1, ave2;
int n1 = data1.length;
int n2 = data2.length;
Avevar av1 = new Avevar( data1 );
ave1 = av1.ave;
var1 = av1.var;
Avevar av2 = new Avevar( data2 );
ave2 = av2.ave;
var2 = av2.var;
df = n1 + n2 -2;
svar = ((n1-1) * var1 + (n2-1)*var2)/df;
t=(ave1-ave2)/Math.sqrt( svar * (1.0/n1 + 1.0/n2));
prob = betai( 0.5 * df, 0.5, df / ( df + t * t ));
return prob;
}
static double tptest(float[] data1, float[] data2)
{
int j;
double var1,var2,ave1,ave2,sd,df,cov=0.0;
double t, prob;
int n=data1.length;
Avevar av1 = new Avevar( data1 );
ave1 = av1.ave;
var1 = av1.var;
Avevar av2 = new Avevar( data2 );
ave2 = av2.ave;
var2 = av2.var;
for (j=0;j<n;j++)
cov += (data1[j]-ave1)*(data2[j]-ave2);
cov /= df=n-1;
sd=Math.sqrt((var1+var2-2.0*cov)/n);
t=(ave1-ave2)/sd;
prob=betai(0.5*df,0.5,df/(df+t*t));
return prob;
}
static double ttest(float[] data1, float[] data2)
{
boolean nonZero = false;
for ( int x=0; x < data1.length && ! nonZero; x++ )
if ( data1[x] != 0 )
nonZero = true;
for ( int x=0; x < data2.length && ! nonZero; x++ )
if ( data2[x] != 0 )
nonZero = true;
if ( ! nonZero )
return 1;
double t;
double prob;
double var1, var2, svar, df, ave1, ave2;
int n1 = data1.length;
int n2 = data2.length;
Avevar av1 = new Avevar( data1 );
ave1 = av1.ave;
var1 = av1.var;
Avevar av2 = new Avevar( data2 );
ave2 = av2.ave;
var2 = av2.var;
df = n1 + n2 -2;
svar = ((n1-1) * var1 + (n2-1)*var2)/df;
t=(ave1-ave2)/Math.sqrt( svar * (1.0/n1 + 1.0/n2));
prob = betai( 0.5 * df, 0.5, df / ( df + t * t ));
return prob;
}
/** Calculates mean and variance from an array of doubles
*/
static class Avevar
{
double ave;
double var;
Avevar( double[] data )
{
double s, ep;
int j;
ave = 0.0;
for ( j=0; j < data.length; j++ ) ave += data[j];
ave /= data.length;
var = ep = 00;
for ( j = 0; j < data.length; j++) {
s = data[j] - ave;
ep += s;
var += s*s;
}
var = ( var - ep * ep / data.length ) / ( data.length - 1);
}
Avevar( float[] data )
{
double s, ep;
int j;
ave = 0.0;
for ( j=0; j < data.length; j++ ) ave += data[j];
ave /= data.length;
var = ep = 00;
for ( j = 0; j < data.length; j++) {
s = data[j] - ave;
ep += s;
var += s*s;
}
var = ( var - ep * ep / data.length ) / ( data.length - 1);
}
}
}
| 7,553 | 20.644699 | 112 | java |
cobs | cobs-master/cobs/utils/Pearson.java |
/**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
import java.util.ArrayList;
import java.util.List;
public class Pearson
{
public static final double TINY=1.0e-20;
public static double getCovariance(double[] x, double[] y)
throws Exception
{
if( x.length != y.length)
throw new Exception("Expecting equal vector lengths");
int j;
double yt,xt;
double sxy=0.0,ay=0.0,ax=0.0;
int n=x.length;
for (j=0;j<n;j++) {
ax += x[j];
ay += y[j];
}
ax /= n;
ay /= n;
for (j=0;j<n;j++) {
xt=x[j]-ax;
yt=y[j]-ay;
sxy += xt*yt;
}
return sxy/(n-1);
}
public static double getPearsonR(List<? extends Number> x, List<? extends Number> y)
{
int j;
double yt,xt;
double syy=0.0,sxy=0.0,sxx=0.0,ay=0.0,ax=0.0;
int n=x.size();
for (j=0;j<n;j++) {
ax += x.get(j).doubleValue();
ay += y.get(j).doubleValue();
}
ax /= n;
ay /= n;
for (j=0;j<n;j++) {
xt=x.get(j).doubleValue()-ax;
yt=y.get(j).doubleValue()-ay;
sxx += xt*xt;
syy += yt*yt;
sxy += xt*yt;
}
return sxy/(Math.sqrt(sxx*syy)+TINY);
}
public static double getPearsonR(ArrayList<Double> x, ArrayList<Double> y)
{
int j;
double yt,xt;
double syy=0.0,sxy=0.0,sxx=0.0,ay=0.0,ax=0.0;
int n=x.size();
for (j=0;j<n;j++) {
ax += x.get(j).doubleValue();
ay += y.get(j).doubleValue();
}
ax /= n;
ay /= n;
for (j=0;j<n;j++) {
xt=x.get(j).doubleValue()-ax;
yt=y.get(j).doubleValue()-ay;
sxx += xt*xt;
syy += yt*yt;
sxy += xt*yt;
}
return sxy/(Math.sqrt(sxx*syy)+TINY);
}
public static double getPearsonR(double[] x, double[] y)
{
int j;
double yt,xt;
double syy=0.0,sxy=0.0,sxx=0.0,ay=0.0,ax=0.0;
int n=x.length;
for (j=0;j<n;j++) {
ax += x[j];
ay += y[j];
}
ax /= n;
ay /= n;
for (j=0;j<n;j++) {
xt=x[j]-ax;
yt=y[j]-ay;
sxx += xt*xt;
syy += yt*yt;
sxy += xt*yt;
}
return sxy/(Math.sqrt(sxx*syy)+TINY);
}
/*
* NEED TO TEST
*/
public static double getPearsonR(double[] x,
double[] y,
int leftCutoff,
int rightCutoff,
int xOffset) throws Exception
{
if( x.length != y.length )
throw new Exception("Error! Cannot generate Pearson for arrays of different lengths " +
x.length + " " + y.length + " "+ leftCutoff + " " + rightCutoff + " " + xOffset);
int j;
double yt,xt;
double syy=0.0,sxy=0.0,sxx=0.0,ay=0.0,ax=0.0;
int n=x.length - leftCutoff - rightCutoff;
for (j=leftCutoff;j<x.length - rightCutoff;j++) {
ax += x[j+xOffset];
ay += y[j];
}
ax /= n;
ay /= n;
for (j=leftCutoff;j<x.length - rightCutoff;j++) {
xt=x[j+xOffset]-ax;
yt=y[j]-ay;
sxx += xt*xt;
syy += yt*yt;
sxy += xt*yt;
}
return sxy/(Math.sqrt(sxx*syy)+TINY);
}
/*
* NEED TO TEST
*/
public static double getPearsonR(float[] x,
float[] y,
int leftCutoff,
int rightCutoff,
int xOffset)
{
int j;
double yt,xt;
double syy=0.0,sxy=0.0,sxx=0.0,ay=0.0,ax=0.0;
int n=x.length - leftCutoff - rightCutoff;
for (j=leftCutoff;j<x.length - rightCutoff;j++) {
ax += x[j+xOffset];
ay += y[j];
}
ax /= n;
ay /= n;
for (j=leftCutoff;j<x.length - rightCutoff;j++) {
xt=x[j+xOffset]-ax;
yt=y[j]-ay;
sxx += xt*xt;
syy += yt*yt;
sxy += xt*yt;
}
return sxy/(Math.sqrt(sxx*syy)+TINY);
}
public static double getPearsonRFromFloat(List<Float> x, List<Float> y)
{
int j;
double yt,xt;
double syy=0.0,sxy=0.0,sxx=0.0,ay=0.0,ax=0.0;
int n=x.size();
for (j=0;j<n;j++) {
ax += x.get(j).doubleValue();
ay += y.get(j).doubleValue();
}
ax /= n;
ay /= n;
for (j=0;j<n;j++) {
xt=x.get(j).doubleValue()-ax;
yt=y.get(j).doubleValue()-ay;
sxx += xt*xt;
syy += yt*yt;
sxy += xt*yt;
}
return sxy/(Math.sqrt(sxx*syy)+TINY);
}
public static double getPearsonRFromNumber(List<Number> x, List<Number> y)
{
int j;
double yt,xt;
double syy=0.0,sxy=0.0,sxx=0.0,ay=0.0,ax=0.0;
int n=x.size();
for (j=0;j<n;j++) {
ax += x.get(j).doubleValue();
ay += y.get(j).doubleValue();
}
ax /= n;
ay /= n;
for (j=0;j<n;j++) {
xt=x.get(j).doubleValue()-ax;
yt=y.get(j).doubleValue()-ay;
sxx += xt*xt;
syy += yt*yt;
sxy += xt*yt;
}
return sxy/(Math.sqrt(sxx*syy)+TINY);
}
}
| 6,864 | 27.966245 | 95 | java |
cobs | cobs-master/cobs/utils/SequenceUtils.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import covariance.datacontainers.PdbChain;
import covariance.datacontainers.PdbFileWrapper;
import covariance.datacontainers.PdbResidue;
import covariance.parsers.PFamPdbAnnotationParser;
public class SequenceUtils
{
private static float[] maxSurfaceAreas = {
188.789f,
200.211f,
226.145f,
265.54f,
301.605f,
155.998f,
246.736f,
247.242f,
291.399f,
254.034f,
280.255f,
238.508f,
216.448f,
252.54f,
309.349f,
196.96f,
215.754f,
223.66f,
281.692f,
300.091f };
// static access only
private SequenceUtils()
{
}
public static boolean isHydrophicChar( char inChar )
{
if ( inChar == 'A' || inChar == 'V' || inChar == 'L'
|| inChar == 'I' || inChar =='F' || inChar =='W'
|| inChar == 'M' || inChar == 'P')
return true;
return false;
}
public static String stripSpaces( String inString )
{
StringBuffer buff = new StringBuffer();
StringTokenizer sToken = new StringTokenizer( inString );
while ( sToken.hasMoreElements() )
buff.append(sToken.nextToken());
return buff.toString();
}
public static boolean pairIsHydrophobic( char inChar1, char inChar2 )
{
if ( isHydrophicChar(inChar1) && isHydrophicChar(inChar2) )
return true;
return false;
}
public static String buildFasta(String sequence1, String sequence2 )
{ StringBuffer buff = new StringBuffer();
buff.append(">1\n");
buff.append( sequence1 + "\n" );
buff.append(">2\n");
buff.append( sequence2 + "\n" );
return buff.toString();
}
public static String fileToString( File file ) throws Exception
{
BufferedReader reader = new BufferedReader( new FileReader( file ));
StringWriter writer = new StringWriter();
char[] c = new char[2048];
int bytesRead;
while ( ( bytesRead = reader.read(c,0,c.length)) != -1 )
writer.write( c, 0, bytesRead );
return writer.toString();
}
public static int threeToIndex( String inString ) throws Exception
{
return MapResiduesToIndex.getIndex( threeToOne( inString ) );
}
public static String threeToOne( String inString ) throws Exception
{
inString = inString.toUpperCase();
if ( inString.equals("GLY") )
return "G";
if ( inString.equals("ALA" ))
return "A";
if ( inString.equals("VAL"))
return "V";
if ( inString.equals("LEU"))
return "L";
if ( inString.equals("ILE" ))
return "I";
if ( inString.equals("PHE" ))
return "F";
if ( inString.equals("TYR" ))
return "Y";
if ( inString.equals("TRP" ))
return "W";
if ( inString.equals("SER" ))
return "S";
if ( inString.equals("THR" ))
return "T";
if ( inString.equals("MET" ))
return "M";
if ( inString.equals("CYS" ))
return "C";
if ( inString.equals("ASN" ))
return "N";
if ( inString.equals("GLN" ))
return "Q";
if ( inString.equals("PRO" ))
return "P";
if ( inString.equals("ASP" ))
return "D";
if ( inString.equals("GLU" ))
return "E";
if ( inString.equals("LYS" ))
return "K";
if ( inString.equals("ARG" ))
return "R";
if ( inString.equals("HIS" ))
return "H";
throw new Exception("Unexpected token '" + inString + "'" );
}
public static String getPdbStringFragment( PFamPdbAnnotationParser parser, PdbFileWrapper pdbWrapper )
{
StringBuffer buff = new StringBuffer();
PdbChain chain = (PdbChain) pdbWrapper.getChain(parser.getChainChar());
if ( chain == null )
return null;
for ( int x=parser.getStartPos(); x <= parser.getEndPos(); x++ )
{
PdbResidue residue = chain.getPdbResidueByPdbPosition(x);
if ( residue != null )
buff.append( residue.getPdbChar());
}
return buff.toString();
}
public static String getPdbStringFragment( char chainChar,
int startPosition,
int endPosition,
PdbFileWrapper pdbWrapper )
{
StringBuffer buff = new StringBuffer();
PdbChain chain = (PdbChain) pdbWrapper.getChain(chainChar);
if ( chain == null )
return null;
for ( int x=startPosition; x <= endPosition; x++ )
{
PdbResidue residue = chain.getPdbResidueByPdbPosition(x);
if ( residue != null )
buff.append( residue.getPdbChar());
}
return buff.toString();
}
/** Removes dupliace chains. If there are two identical chains from the same pdb,
* the shortest one is removed.
*
* Made public and static for testing purposes ( I find I am missing the C++ friend! )
*/
public static void trimPdbIDs(List pdbIds) throws Exception
{
List listCopy = new ArrayList( pdbIds );
for ( Iterator i = listCopy.iterator();
i.hasNext(); )
{
PFamPdbAnnotationParser s1 = new PFamPdbAnnotationParser( i.next().toString());
for ( Iterator i2 = listCopy.iterator();
i2.hasNext(); )
{
PFamPdbAnnotationParser s2 = new PFamPdbAnnotationParser( i2.next().toString());
if ( ! s1.equals(s2) )
{
if ( s1.getChainChar()== s2.getChainChar() &&
s1.getFourCharId().equals( s2.getFourCharId()) )
{
if ( s1.getLength() > s2.getLength() )
pdbIds.remove(s2.getPdbAnnotationString());
else
pdbIds.remove(s1.getPdbAnnotationString());
}
}
}
}
}
}
| 6,195 | 22.033457 | 103 | java |
cobs | cobs-master/cobs/utils/Factorials.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
import java.math.BigDecimal;
import java.math.BigInteger;
public class Factorials
{
private static BigInteger[] factorials = null;
public static final int NUM_TO_CALCULATE=171;
public static BigInteger getFactorial( int n ) throws Exception
{
if ( n < 0 )
throw new Exception("Error n must be positive");
if ( n >= NUM_TO_CALCULATE )
throw new Exception("Error! We only caclulated to n=" + (NUM_TO_CALCULATE-1) );
return getFactorialArray()[n];
}
/** returns ( N! / (N-n)!n! ) * p^n * ( 1- p)^(N-n)
*/
public static BigDecimal getBinomial( int N, int n, float p ) throws Exception
{
BigInteger firstTerm = choose(N,n);
BigDecimal returnVal = new BigDecimal( Math.pow(p, n ));
returnVal = returnVal.multiply( new BigDecimal ( Math.pow((1-p), N-n)));
returnVal = returnVal.multiply( new BigDecimal( firstTerm));
return returnVal;
}
public static double getLnBinomial( int N, int n, float p ) throws Exception
{
double val = getLnChoose(N,n);
val += Math.log(Math.pow(p,n));
val += Math.log(Math.pow((1-p), N-n));
return val;
}
private static synchronized BigInteger[] getFactorialArray()
{
if ( factorials == null )
{
factorials = new BigInteger[ NUM_TO_CALCULATE];
factorials[0] = new BigInteger( "1" );
for ( int x=1; x<NUM_TO_CALCULATE; x++ )
{
factorials[x] = factorials[x-1].multiply( new BigInteger( "" + x ));
}
}
return factorials;
}
// singleton only
private Factorials()
{
}
public static boolean canDoIt( int N, int n ) throws Exception
{
int biggest = n;
int smallest = N - n;
if ( smallest > biggest )
{
biggest = N - n;
smallest = n;
}
if ( smallest > NUM_TO_CALCULATE )
return false;
return true;
}
public static double getLnChoose( int N, int n) throws Exception
{
if ( n > N )
throw new Exception("Error! N must be >= n " + "N=" + N + " n=" + n);
if ( N < 0 )
throw new Exception("Error! N must be positive");
if ( N == n || n == 0 )
return Math.log( 1 );
double top = 0;
if ( N < NUM_TO_CALCULATE )
{
top = Math.log(getFactorialArray()[N].doubleValue());
}
else // Stirling's approximation
{
top = N * Math.log( N ) - N;
}
double bottom = 0;
if ( N - n < NUM_TO_CALCULATE )
{
bottom = Math.log( getFactorialArray()[N-n].doubleValue() );
}
else
{
int NMinusN = N-n;
bottom = (NMinusN ) * Math.log( NMinusN ) - NMinusN ;
}
if ( n < NUM_TO_CALCULATE )
{
bottom += Math.log( getFactorialArray()[n].doubleValue());
}
else
{
bottom += n * Math.log(n) - n;
}
return top - bottom;
}
/** returns N! / ( N-n)!n!
*/
public static BigInteger choose( int N, int n ) throws Exception
{
if ( n > N )
throw new Exception("Error! N must be >= n");
if ( N < 0 )
throw new Exception("Error! N must be positive");
if ( N == n || n == 0 )
return new BigInteger( "" + 1 );
if ( N >= NUM_TO_CALCULATE )
{
int biggest = n;
int smallest = N - n;
if ( smallest > biggest )
{
biggest = N - n;
smallest = n;
}
if ( smallest > NUM_TO_CALCULATE )
throw new Exception("Error! Need to have " + smallest + " factorial ");
int x = N-1;
BigInteger top = new BigInteger("" + N );
while ( x > biggest )
{
top = top.multiply( new BigInteger( "" + x ) );
x--;
}
return top.divide( getFactorialArray()[smallest] );
}
else
{
BigInteger top = getFactorialArray()[N];
BigInteger bottom = getFactorialArray()[N-n];
bottom = bottom.multiply( getFactorialArray()[n]);
return top.divide( bottom );
}
}
public static double getBinomialSum(int N, int n, float prob ) throws Exception
{
BigDecimal sum = new BigDecimal( 0 );
for ( int x=n; x<=N; x++ )
sum= sum.add( Factorials.getBinomial(N,x,prob));
return sum.doubleValue();
}
public static void main(String[] args) throws Exception
{
System.out.println( "" + getBinomialSum(19,5,.074f));
}
}
| 4,732 | 21.754808 | 83 | java |
cobs | cobs-master/cobs/utils/ConfigReader.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package utils;
import java.io.*;
import java.util.*;
public class ConfigReader
{
public static final String ENERGETICS_PROPERTIES_FILE="Energetics.properties";
public static final String CLUSTAL_EXECUTABLE="CLUSTAL_EXECUTABLE";
public static final String CLUSTAL_DIRECTORY="CLUSTAL_DIRECTORY";
public static final String COBS_HOME_DIRECTORY="COBS_HOME_DIRECTORY";
public static final String FULL_PFAM_PATH="FULL_PFAM_PATH";
public static final String OUT_DATA_DIR="OUT_DATA_DIR";
public static final String GZIP_FULL_PATH="GZIP_FULL_PATH";
public static final String COBS_CLEANROOM = "COBS_CLEANROOM";
public static final String PDB_DIR = "PDB_DIR";
public static final String BLAST_DIR = "BLAST_DIR";
public static final String PDB_PFAM_CHAIN = "PDB_PFAM_CHAIN";
public static final String NUM_THREADS = "NUM_THREADS";
public static final String WRITE_GZIPPED_RESULTS = "WRITE_GZIPPED_RESULTS";
public static final String TRUE="TRUE";
public static final String YES="YES";
private static ConfigReader configReader = null;
private static Properties props = new Properties();
private static String getAProperty(String namedProperty ) throws Exception
{
Object obj = props.get( namedProperty );
if ( obj == null )
throw new Exception("Error! Could not find " + namedProperty + " in " + ENERGETICS_PROPERTIES_FILE );
return obj.toString();
}
private ConfigReader() throws Exception
{
Object o = new Object();
InputStream in = o.getClass().getClassLoader().getSystemResourceAsStream( ENERGETICS_PROPERTIES_FILE );
if ( in == null )
throw new Exception("Error! Could not find " + ENERGETICS_PROPERTIES_FILE + " anywhere on the current classpath");
BufferedReader reader = new BufferedReader( new InputStreamReader( in ));
props = new Properties();
String nextLine = reader.readLine();
while ( nextLine != null )
{
nextLine= nextLine.trim();
if ( nextLine.length() > 0 && ! nextLine.startsWith("!") && ! nextLine.startsWith("#") )
{
StringTokenizer sToken = new StringTokenizer( nextLine, "=" );
if ( sToken.hasMoreTokens() )
{
String key = sToken.nextToken().trim();
String value = "";
if ( sToken.hasMoreTokens() )
{
value = sToken.nextToken().trim();
}
props.put( key, value );
}
}
nextLine = reader.readLine();
}
}
private static synchronized ConfigReader getConfigReader() throws Exception
{
if ( configReader == null )
{
configReader = new ConfigReader();
}
return configReader;
}
public static String getCobsHomeDirectory() throws Exception
{
return getConfigReader().getAProperty( COBS_HOME_DIRECTORY );
}
public static String getFullPfamPath() throws Exception
{
return getConfigReader().getAProperty( FULL_PFAM_PATH );
}
public static String getPdbDir() throws Exception
{
return getConfigReader().getAProperty( PDB_DIR);
}
public static String getOutDataDir() throws Exception
{
return getConfigReader().getAProperty( OUT_DATA_DIR );
}
public static String getClustalExecutable() throws Exception
{
return getConfigReader().getAProperty( CLUSTAL_EXECUTABLE);
}
public static String getClustalDirectory() throws Exception
{
return getConfigReader().getAProperty( CLUSTAL_DIRECTORY);
}
public static String getBlastDir() throws Exception
{
return getConfigReader().getAProperty(BLAST_DIR);
}
public static String getCleanroom() throws Exception
{
return getConfigReader().getAProperty(COBS_CLEANROOM);
}
public static String getPdbPfamChain() throws Exception {
return getConfigReader().getAProperty(PDB_PFAM_CHAIN);
}
/*
* Defaluts to 1 - does not throw
*/
public static int getNumThreads()
{
try
{
System.out.println("Trying to read number of threads " );
int numThreads = Integer.parseInt(getConfigReader().getAProperty(NUM_THREADS));
System.out.println("Got " + numThreads + " threads ");
return numThreads;
}
catch(Exception ex)
{
System.out.println("Could not read " + NUM_THREADS + " which must be an integer.");
System.out.println("Defaulting to single thread behavior ");
return 1;
}
}
public static boolean writeZippedResults()
{
try
{
String zipString = getConfigReader().getAProperty(WRITE_GZIPPED_RESULTS).toUpperCase();
if( zipString.equals(TRUE) || zipString.equals(YES))
return true;
}
catch(Exception ex)
{
return false;
}
return false;
}
}
| 5,173 | 26.231579 | 120 | java |
cobs | cobs-master/cobs/gocAlgorithms/COBSFromNW.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package gocAlgorithms;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import utils.ConfigReader;
import utils.Pearson;
import covariance.parsers.FastaSequence;
import dynamicProgramming.MaxhomSubstitutionMatrix;
import dynamicProgramming.NeedlemanWunsch;
import dynamicProgramming.PairedAlignment;
public class COBSFromNW
{
private static int[] getTranslationArray( List<FastaSequence> alignment )
{
FastaSequence fs = null;
for(FastaSequence fSeq : alignment)
if(fSeq.getFirstTokenOfHeader().equals("SAHH_PLAF7"))
fs = fSeq;
String strippedString = fs.getSequence().replaceAll("-", "");
System.out.println(strippedString);
System.out.println(strippedString.length());
int[] returnArray = new int[strippedString.length()];
int index =0;
for( int x=0; x < fs.getSequence().length(); x++)
{
char c= fs.getSequence().charAt(x);
if( c != '-')
{
returnArray[index] = x;
index++;
}
}
for( int x=0; x < returnArray.length; x++)
System.out.println( x + " " + returnArray[x]);
return returnArray;
}
public static void main(String[] args) throws Exception
{
List<FastaSequence> alignment =
FastaSequence.readFastaFile(ConfigReader.getCleanroom() + File.separator +
"AdoHcyase.fasta");
int[] translationArray = getTranslationArray(alignment);
MaxhomSubstitutionMatrix substitutionMatrix = new MaxhomSubstitutionMatrix();
int length = alignment.get(0).getSequence().length();
for( FastaSequence fs : alignment)
if (fs.getSequence().length() != length)
throw new Exception("No");
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(
ConfigReader.getCleanroom() + File.separator +
"comparison.txt")));
writer.write("kyleScore\tscoreFromGlobalAlignment\n");
BufferedReader reader = new BufferedReader(new FileReader(new File(
ConfigReader.getCleanroom() + File.separator +
"AdoHcyase.fasta.output.csv")));
reader.readLine();
for(String s = reader.readLine();
s != null;
s = reader.readLine())
{
String[] splits = s.split(",");
double sum =
getScoreFromGlobalAlignment(
alignment,
Integer.parseInt(splits[1]),
Integer.parseInt(splits[2]),
Integer.parseInt(splits[3]),
Integer.parseInt(splits[4]),
substitutionMatrix,
translationArray);
writer.write(splits[9] + "\t");
writer.write(sum + "\n");
writer.flush();
}
reader.readLine();
reader.close();
}
private static double getScoreFromGlobalAlignment( List<FastaSequence> alignment,
int leftPosStart, int leftPosEnd, int rightPosStart, int rightPosEnd,
MaxhomSubstitutionMatrix substitutionMatrix, int[] translationArray)
throws Exception
{
List<Double> list1 = new ArrayList<Double>();
List<Double> list2 = new ArrayList<Double>();
leftPosStart--;
rightPosStart--;
leftPosEnd--;
rightPosEnd--;
for(int x=0; x < alignment.size()-1; x++)
{
if( x %100 ==0 )
System.out.println("\t\t\t" + x);
FastaSequence fs1 = alignment.get(x);
String leftFrag1 = fs1.getSequence().substring( translationArray[leftPosStart],
translationArray[leftPosEnd] + 1 );
String rightFrag1 =fs1.getSequence().substring(
translationArray[rightPosStart],
translationArray[ rightPosEnd] +1 );
for( int y=x+1; y < alignment.size(); y++)
{
FastaSequence fs2 = alignment.get(y);
String leftFrag2 = fs2.getSequence().substring(
translationArray[leftPosStart], translationArray[ leftPosEnd ] + 1 );
String rightFrag2 =fs2.getSequence().substring(
translationArray[ rightPosStart], translationArray[ rightPosEnd] + 1);
PairedAlignment leftPa =
NeedlemanWunsch.globalAlignTwoSequences(
leftFrag1, leftFrag2, substitutionMatrix, -3, -1, false);
list1.add((double)leftPa.getAlignmentScore());
PairedAlignment rightPa =
NeedlemanWunsch.globalAlignTwoSequences(
rightFrag1, rightFrag2, substitutionMatrix, -3, -1, false);
list2.add((double) rightPa.getAlignmentScore());
}
}
return Pearson.getPearsonR(list1, list2);
}
}
| 4,982 | 27.637931 | 83 | java |
cobs | cobs-master/cobs/gocAlgorithms/COBS.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package gocAlgorithms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import utils.MapResiduesToIndex;
import utils.Pearson;
import covariance.algorithms.McBASCCovariance;
import covariance.datacontainers.Alignment;
import covariance.parsers.FastaSequence;
public class COBS implements GroupOfColumnsInterface
{
private static int[][] substitutionMatrix;
static
{
try
{
substitutionMatrix = McBASCCovariance.getMaxhomMetric();
}
catch(Exception ex)
{
ex.printStackTrace();
System.exit(1);
}
}
/*
* Made public to allow for testing by test.TestCobs
*/
public static double getSubstitutionMatrixSum( String s1, String s2 , int[][] substitutionMatrix)
throws Exception
{
if(s1.length() != s2.length())
throw new Exception("No");
double sum = 0D;
for( int x=0; x < s1.length(); x++)
{
int index1 = MapResiduesToIndex.getIndexOrNegativeOne(s1.charAt(x));
if( index1 != -1)
{
int index2 = MapResiduesToIndex.getIndexOrNegativeOne(s2.charAt(x));
if( index2 != -1)
sum += substitutionMatrix[index1][index2];
}
}
return sum;
}
@Override
public String getName()
{
return "COBS_UNCORRECTED";
}
@Override
public double getScore(Alignment a, int leftPosStart,
int leftPosEnd, int rightPosStart, int rightPosEnd) throws Exception
{
return getScoreFromGlobalAlignment(a.getAsFastaSequenceList(),
leftPosStart, leftPosEnd, rightPosStart, rightPosEnd, substitutionMatrix);
}
private static double getScoreFromGlobalAlignment( List<FastaSequence> alignment,
int leftPosStart, int leftPosEnd, int rightPosStart, int rightPosEnd,
int[][] substitutionMatrix)
throws Exception
{
/**
* Many comparisons as we "walk" down the permutations in a given set of columns will be identical. We can save at LEAST
* 10x of computations if we cache the results as a simple concatenation (with a comma) of the strings and use those scores
* instead of recomputing the lookups etc. This uses more memory, but is a worthy tradeoff.
*/
HashMap<String,Double> previouslyCalculatedScores = new HashMap<String,Double>();
List<Double> list1 = new ArrayList<Double>();
List<Double> list2 = new ArrayList<Double>();
leftPosStart--;;
rightPosStart--;
for(int x=0; x < alignment.size()-1; x++)
{
FastaSequence fs1 = alignment.get(x);
String leftFrag1 = fs1.getSequence().substring(leftPosStart, leftPosEnd );
String rightFrag1 =fs1.getSequence().substring(rightPosStart, rightPosEnd);
for( int y=x+1; y < alignment.size(); y++)
{
FastaSequence fs2 = alignment.get(y);
String leftFrag2 = fs2.getSequence().substring(leftPosStart, leftPosEnd );
String rightFrag2 =fs2.getSequence().substring(rightPosStart, rightPosEnd);
String concatLookupOne = leftFrag1 + "," + leftFrag2;
String concatLookupTwo = rightFrag1 + "," + rightFrag2;
Double matrixOneSum, matrixTwoSum;
if (previouslyCalculatedScores.containsKey(concatLookupOne)){
matrixOneSum = previouslyCalculatedScores.get(concatLookupOne);
//System.err.println("We found matrixONE.");
}
else{
matrixOneSum = getSubstitutionMatrixSum(leftFrag1, leftFrag2, substitutionMatrix);
previouslyCalculatedScores.put(concatLookupOne, matrixOneSum);
}
if (previouslyCalculatedScores.containsKey(concatLookupTwo)){
matrixTwoSum = previouslyCalculatedScores.get(concatLookupTwo);
//System.err.println("We found matrixTWO.");
if ((matrixOneSum == null) || (matrixTwoSum == null)){
continue;
}
list1.add(matrixOneSum);
list2.add(matrixTwoSum);
}
else{
matrixTwoSum = getSubstitutionMatrixSum(rightFrag1, rightFrag2, substitutionMatrix);
if ((matrixOneSum == null) || (matrixTwoSum == null)){
continue;
}
list1.add(matrixOneSum);
list2.add(matrixTwoSum);
previouslyCalculatedScores.put(concatLookupTwo, matrixTwoSum);
}
}
}
if ((list1.size() < 1) || (list2.size() < 1)){
throw new IndexOutOfBoundsException("Unsure what happened, but we don't have functional lists to perform a Pearson Correlation.");
}
return Pearson.getPearsonR(list1, list2);
}
public static void main(String[] args)
{
}
}
| 4,931 | 28.011765 | 133 | java |
cobs | cobs-master/cobs/gocAlgorithms/AverageScoreGenerator.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package gocAlgorithms;
import java.util.HashMap;
import covariance.algorithms.ScoreGenerator;
import covariance.datacontainers.Alignment;
public class AverageScoreGenerator implements GroupOfColumnsInterface
{
private final ScoreGenerator sg;
private final HashMap<String, Double> cachedMap = new HashMap<String, Double>();
public AverageScoreGenerator(ScoreGenerator sg) throws Exception
{
this.sg = sg;
}
@Override
public String getName()
{
return "Average" + sg.getAnalysisName();
}
@Override
/*
* Not thread safe.
*/
public double getScore(Alignment alignment, int leftPosStart,
int leftPosEnd, int rightPosStart, int rightPosEnd)
throws Exception
{
//System.out.println("CHECKING " + alignment.getAligmentID() + " " +
//leftPosStart + " " + leftPosEnd + " " + rightPosStart + " " + rightPosEnd);
if( alignment != sg.getAlignment())
throw new Exception("NO");
double sum =0;
double n =0;
for( int x = leftPosStart; x <= leftPosEnd; x++)
{
for(int y= rightPosStart; y <= rightPosEnd; y++)
{
String key = x + "@" + y;
Double score = cachedMap.get(key);
if( score == null)
{
if( x== y)
System.out.println("Querying " + x + " " + y);
score = sg.getScore(alignment, x, y);
}
cachedMap.put(key, score);
sum += score;
n++;
}
}
return sum / n;
}
} | 2,041 | 23.902439 | 81 | java |
cobs | cobs-master/cobs/gocAlgorithms/AverageMcBASC.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package gocAlgorithms;
import java.util.HashMap;
import covariance.algorithms.McBASCCovariance;
import covariance.datacontainers.Alignment;
public class AverageMcBASC implements GroupOfColumnsInterface
{
private final McBASCCovariance mcBasc;
private final HashMap<String, Double> cachedMap = new HashMap<String, Double>();
private final Alignment a;
public AverageMcBASC(Alignment a) throws Exception
{
this.a = a;
mcBasc = new McBASCCovariance(a);
}
@Override
public String getName()
{
return "AverageMcBASC";
}
@Override
/*
* Not thread safe. Ignores columns with noScore..
*/
public double getScore(Alignment alignment, int leftPosStart,
int leftPosEnd, int rightPosStart, int rightPosEnd)
throws Exception
{
if( a != alignment)
throw new Exception("NO");
double sum =0;
double n =0;
for( int x = leftPosStart; x <= leftPosEnd; x++)
{
for(int y= rightPosStart; y <= rightPosEnd; y++)
{
String key = x + "@" + y;
Double score = cachedMap.get(key);
if( score == null)
{
score = mcBasc.getScore(alignment, x, y);
cachedMap.put(key, score);
}
if( score != mcBasc.NO_SCORE && ! Double.isInfinite(score) && ! Double.isNaN(score))
{
sum += score;
n++;
}
}
}
if( Double.isInfinite(sum) || Double.isNaN(sum) || n==0)
return mcBasc.NO_SCORE;
return sum / n;
}
}
| 2,049 | 23.698795 | 88 | java |
cobs | cobs-master/cobs/gocAlgorithms/GroupOfColumnsInterface.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package gocAlgorithms;
import covariance.datacontainers.Alignment;
public interface GroupOfColumnsInterface
{
public double getScore( Alignment alignment,int leftPosStart, int leftPosEnd, int rightPosStart, int rightPosEnd)
throws Exception;
public String getName();
}
| 919 | 33.074074 | 114 | java |
cobs | cobs-master/cobs/gocAlgorithms/HelixSheetGroup.java | /**
* Authors: anthony.fodor@gmail.com kylekreth@alumni.nd.edu
*
* This code is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version,
* provided that any use properly credits the author.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details at http://www.gnu.org * * */
package gocAlgorithms;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import utils.ConfigReader;
public class HelixSheetGroup implements Comparable<HelixSheetGroup>
{
public static final String HELIX = "HELIX";
public static final String SHEET = "SHEET";
public static final String NONE = "NONE";
private String element;
private int startPos;
private int endPos;
private char startChain;
private char endChain;
@Override
public int compareTo(HelixSheetGroup o)
{
return this.startPos - o.startPos;
}
@Override
public String toString()
{
return element + ":" + startChain + "" + startPos + "-" + endChain + "" + endPos;
}
public char getStartChain()
{
return startChain;
}
public char getEndChain()
{
return endChain;
}
public String getElement()
{
return element;
}
public int getStartPos()
{
return startPos;
}
public int getEndPos()
{
return endPos;
}
public static String getGroup(int pos, List<HelixSheetGroup> list)
{
for( HelixSheetGroup hsg : list )
if( pos >= hsg.startPos && pos <= hsg.endPos)
return hsg.getElement();
return NONE;
}
public static List<HelixSheetGroup> getList(String pdbFile, char pdbChain, int pdbStart, int pdbEnd) throws Exception
{
List<HelixSheetGroup> aList = new ArrayList<HelixSheetGroup>();
for( HelixSheetGroup hsg : getList(pdbFile))
if( hsg.startChain == pdbChain && hsg.endChain == pdbChain && hsg.startPos >= pdbStart && hsg.endPos <= pdbEnd)
aList.add(hsg);
List<HelixSheetGroup> returnList = new ArrayList<HelixSheetGroup>();
for(HelixSheetGroup hsg : aList)
if( ! alreadyThere(hsg, returnList))
returnList.add(hsg);
for(HelixSheetGroup hsg : returnList)
trimMatchingEnds(hsg, returnList);
return returnList;
}
private static boolean alreadyThere( HelixSheetGroup hsg, List<HelixSheetGroup> list )
{
for( HelixSheetGroup aHsg : list )
{
//System.out.println( hsg + " vs " + aHsg);
if( hsg.startPos >= aHsg.startPos && hsg.startPos<= aHsg.endPos)
return true;
if( aHsg.startPos >= hsg.startPos && aHsg.startPos <= hsg.endPos)
return true;
//System.out.println("OK\n\n");
}
return false;
}
private static void trimMatchingEnds( HelixSheetGroup hsg, List<HelixSheetGroup> list )
{
for( HelixSheetGroup aHsg : list )
{
if( aHsg != hsg)
{
//System.out.println("hsg " + hsg);
//System.out.println("ahsg " + aHsg);
//trim if overlapping to avoid residues being compared to themselves
if( aHsg.endPos==hsg.startPos)
aHsg.endPos = --aHsg.endPos;
if( hsg.endPos == aHsg.startPos)
hsg.endPos= --hsg.endPos;
//System.out.println("Post " + aHsg + "\n\n\n");
}
}
}
public static List<HelixSheetGroup> getList(String pdbFile) throws Exception
{
List<HelixSheetGroup> list = new ArrayList<HelixSheetGroup>();
BufferedReader reader = new BufferedReader(new FileReader(new File(pdbFile)));
for(String s= reader.readLine(); s != null; s = reader.readLine())
{
StringTokenizer sToken = new StringTokenizer(s);
String firstToken = sToken.nextToken();
if( firstToken.equals(HELIX) )
{
HelixSheetGroup hsg = new HelixSheetGroup();
hsg.element = new String(firstToken);
hsg.startPos = Integer.parseInt(s.substring(21,25).replaceAll("[A-Z]", "").trim());
hsg.endPos = Integer.parseInt(s.substring(33,37).replaceAll("[A-Z]", "").trim());
hsg.startChain= s.charAt(19);
hsg.endChain = s.charAt(31);
list.add(hsg);
}
else if( firstToken.equals(SHEET) )
{
HelixSheetGroup hsg = new HelixSheetGroup();
hsg.element = new String(firstToken);
hsg.startPos = Integer.parseInt(s.substring(22,26).replaceAll("[A-Z]", "").trim());
hsg.endPos = Integer.parseInt(s.substring(33,37).replaceAll("[A-Z]", "").trim());
hsg.startChain = s.charAt(21);
hsg.endChain = s.charAt(32);
list.add(hsg);
}
}
reader.close();
Collections.sort(list);
return list;
}
public static void main(String[] args) throws Exception
{
List<HelixSheetGroup> list = getList(
ConfigReader.getPdbDir() + File.separator + "1DXJ.txt",'A',1,230);
for( HelixSheetGroup hsg : list)
System.out.println(hsg.element + " " + hsg.startPos + " " + hsg.endPos);
}
}
| 5,119 | 25.25641 | 118 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/CrossvalidatingZoneClassificationEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import libsvm.svm_parameter;
import org.apache.commons.cli.*;
import pl.edu.icm.cermine.evaluation.tools.ClassificationResults;
import pl.edu.icm.cermine.evaluation.tools.DividedEvaluationSet;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.structure.model.BxDocument;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.structure.model.BxZoneLabel;
import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter;
import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader;
import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder;
import pl.edu.icm.cermine.tools.classification.general.TrainingSample;
import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier;
/**
* Class for performing cross-validating classifier performance in zone classification task
*
* @author Pawel Szostek
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public abstract class CrossvalidatingZoneClassificationEvaluator {
private static final EnumMap<BxZoneLabel, BxZoneLabel> DEFAULT_LABEL_MAP = new EnumMap<BxZoneLabel, BxZoneLabel>(BxZoneLabel.class);
static {
for (BxZoneLabel label : BxZoneLabel.values()) {
DEFAULT_LABEL_MAP.put(label, label);
}
}
protected int foldness;
private final Map<BxZoneLabel, BxZoneLabel> labelMap = DEFAULT_LABEL_MAP.clone();
private final TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader();
private final BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter();
public static void main(String[] args, CrossvalidatingZoneClassificationEvaluator evaluator)
throws ParseException, AnalysisException, IOException, TransformationException, CloneNotSupportedException {
Options options = new Options();
options.addOption("compact", false, "do not print results for pages");
options.addOption("fold", true, "foldness of cross-validation");
options.addOption("help", false, "print this help message");
options.addOption("minimal", false, "print only final summary");
options.addOption("full", false, "print all possible messages");
options.addOption("kernel", true, "kernel type");
options.addOption("g", true, "gamma");
options.addOption("C", true, "C");
options.addOption("degree", true, "degree");
options.addOption("ext", true, "ext");
CommandLineParser parser = new DefaultParser();
CommandLine line = parser.parse(options, args);
if (line.hasOption("help")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(args[0] + " [-options] input-file",
options);
} else {
String[] remaining = line.getArgs();
if (remaining.length != 1) {
throw new ParseException("Input file is missing!");
}
if (!line.hasOption("fold")) {
throw new ParseException("Foldness of cross-validation is not given!");
} else {
evaluator.foldness = Integer.parseInt(line.getOptionValue("fold"));
}
String inputFile = remaining[0];
Double C = Double.valueOf(line.getOptionValue("C"));
Double gamma = Double.valueOf(line.getOptionValue("g"));
String degreeStr = line.getOptionValue("degree");
Integer degree = -1;
if (degreeStr != null && !degreeStr.isEmpty()) {
degree = Integer.valueOf(degreeStr);
}
Integer kernelType;
switch(Integer.parseInt(line.getOptionValue("kernel"))) {
case 0: kernelType = svm_parameter.LINEAR; break;
case 1: kernelType = svm_parameter.POLY; break;
case 2: kernelType = svm_parameter.RBF; break;
case 3: kernelType = svm_parameter.SIGMOID; break;
default:
throw new IllegalArgumentException("Invalid kernel value provided");
}
evaluator.setLabelMap(BxZoneLabel.getLabelToGeneralMap());
evaluator.run(inputFile, line.getOptionValue("ext"), kernelType, gamma, C, degree);
}
}
protected abstract List<TrainingSample<BxZoneLabel>> getSamples(String inputFile, String ext) throws AnalysisException;
public void run(String inputFile, String ext, int kernelType, double gamma, double C, int degree) throws AnalysisException, IOException, TransformationException, CloneNotSupportedException {
ClassificationResults summary = newResults();
List<TrainingSample<BxZoneLabel>> samples = getSamples(inputFile, ext);
List<DividedEvaluationSet> sampleSets = DividedEvaluationSet.build(samples, foldness);
System.out.println("All training elements: " + samples.size());
for (int fold = 0; fold < foldness; ++fold) {
List<TrainingSample<BxZoneLabel>> trainingSamples = sampleSets.get(fold).getTrainingDocuments();
List<TrainingSample<BxZoneLabel>> testSamples = sampleSets.get(fold).getTestDocuments();
System.out.println("Fold number " + fold);
System.out.println("Training elements " + trainingSamples.size());
System.out.println("Test elements " + testSamples.size());
ClassificationResults iterationResults = newResults();
SVMZoneClassifier zoneClassifier = getZoneClassifier(trainingSamples, kernelType, gamma, C, degree);
for (TrainingSample<BxZoneLabel> testSample : testSamples) {
BxZoneLabel expectedClass = testSample.getLabel();
BxZoneLabel inferedClass = zoneClassifier.predictLabel(testSample);
ClassificationResults documentResults = compareItems(expectedClass, inferedClass);
iterationResults.add(documentResults);
if (!expectedClass.equals(inferedClass)) {
System.out.println("Expected " + expectedClass + ", got " + inferedClass);
System.out.println(testSample.getData() + "\n");
}
}
summary.add(iterationResults);
System.out.println("=== Single iteration summary (" + (fold + 1) + "/" + this.foldness + ")");
printFinalResults(iterationResults);
}
System.out.println("=== General summary (" + this.foldness + " iterations)");
printFinalResults(summary);
System.out.println("F score "+summary.getMeanF1Score());
}
protected ClassificationResults newResults() {
return new ClassificationResults();
}
protected ClassificationResults compareItems(BxZoneLabel expected, BxZoneLabel actual) {
ClassificationResults pageResults = newResults();
pageResults.addOneZoneResult(expected, actual);
return pageResults;
}
protected BxDocument readDocument(Reader input) throws TransformationException {
List<BxPage> pages = reader.read(input);
BxDocument ret = new BxDocument();
for (BxPage page : pages) {
page.setParent(ret);
}
return ret.setPages(pages);
}
public void setLabelMap(Map<BxZoneLabel, BxZoneLabel> value) {
labelMap.putAll(DEFAULT_LABEL_MAP);
labelMap.putAll(value);
}
protected void writeDocument(BxDocument document, Writer output) throws TransformationException {
writer.write(output, Lists.newArrayList(document));
}
protected void printItemResults(BxZone expected, BxZone actual) {
if (expected.getLabel() != actual.getLabel()) {
System.out.println("Expected " + expected.getLabel() + ", got " + actual.getLabel());
System.out.println(expected.toText() + "\n");
}
}
protected void printDocumentResults(ClassificationResults results) {
results.printLongSummary();
results.printShortSummary();
}
protected void printFinalResults(ClassificationResults results) {
results.printMatrix();
results.printLongSummary();
results.printShortSummary();
results.printQualityMeasures();
}
protected abstract SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree)
throws AnalysisException, IOException, CloneNotSupportedException;
protected abstract FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder();
}
| 9,673 | 43.995349 | 194 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/ReferenceParsingEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import org.jdom.JDOMException;
import org.xml.sax.InputSource;
import pl.edu.icm.cermine.bibref.CRFBibReferenceParser;
import pl.edu.icm.cermine.bibref.model.BibEntry;
import pl.edu.icm.cermine.bibref.model.BibEntryFieldType;
import pl.edu.icm.cermine.bibref.parsing.model.Citation;
import pl.edu.icm.cermine.bibref.parsing.tools.CitationUtils;
import pl.edu.icm.cermine.bibref.parsing.tools.NlmCitationExtractor;
import pl.edu.icm.cermine.exception.AnalysisException;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ReferenceParsingEvaluator {
public static void main(String[] args) throws JDOMException, IOException, AnalysisException {
if (args.length != 3) {
System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>");
System.exit(1);
}
int foldness = Integer.parseInt(args[0]);
String modelPathSuffix = args[1];
String testPathSuffix = args[2];
Map<BibEntryFieldType, List<Result>> results =
new EnumMap<BibEntryFieldType, List<Result>>(BibEntryFieldType.class);
for (int i = 0; i < foldness; i++) {
System.out.println("Fold "+i);
String modelPath = modelPathSuffix + i;
String termsPath = modelPathSuffix + "terms" + i;
String journalsPath = modelPathSuffix + "journals" + i;
String surnamesPath = modelPathSuffix + "surnames" + i;
String institutionsPath = modelPathSuffix + "institutions" + i;
CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath, termsPath, journalsPath, surnamesPath, institutionsPath);
String testPath = testPathSuffix + i;
File testFile = new File(testPath);
List<Citation> testCitations;
InputStream testIS = null;
try {
testIS = new FileInputStream(testFile);
InputSource testSource = new InputSource(testIS);
testCitations = NlmCitationExtractor.extractCitations(testSource);
} finally {
if (testIS != null) {
testIS.close();
}
}
System.out.println(testCitations.size());
List<BibEntry> testEntries = new ArrayList<BibEntry>();
for (Citation c : testCitations) {
BibEntry entry = CitationUtils.citationToBibref(c);
testEntries.add(entry);
for (BibEntryFieldType key : entry.getFieldKeys()) {
if (results.get(key) == null) {
results.put(key, new ArrayList<Result>());
}
}
}
int j = 0;
for (BibEntry orig : testEntries) {
BibEntry test = parser.parseBibReference(orig.getText());
System.out.println();
System.out.println();
System.out.println(orig.toBibTeX());
System.out.println(test.toBibTeX());
Map<BibEntryFieldType, Result> map =
new EnumMap<BibEntryFieldType, Result>(BibEntryFieldType.class);
for (BibEntryFieldType s : orig.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addOrig(orig.getAllFieldValues(s).size());
}
for (BibEntryFieldType s : test.getFieldKeys()) {
if (map.get(s) == null) {
map.put(s, new Result());
}
map.get(s).addExtr(test.getAllFieldValues(s).size());
}
for (BibEntryFieldType s : test.getFieldKeys()) {
List<String> origVals = orig.getAllFieldValues(s);
for (String testVal : test.getAllFieldValues(s)) {
boolean found = false;
if (origVals.contains(testVal)) {
map.get(s).addSuccess();
origVals.remove(testVal);
found = true;
}
if (!found) {
System.out.println("WRONG "+s);
}
}
}
for (Map.Entry<BibEntryFieldType, Result> s : map.entrySet()) {
System.out.println("");
System.out.println(s.getKey());
System.out.println(s.getValue());
System.out.println(s.getValue().getPrecision());
System.out.println(s.getValue().getRecall());
results.get(s.getKey()).add(s.getValue());
}
j++;
System.out.println("Tested "+j+" out of "+testEntries.size());
}
}
for (Map.Entry<BibEntryFieldType, List<Result>> e : results.entrySet()) {
System.out.println("");
System.out.println(e.getKey());
System.out.println(e.getValue().size());
double precision = 0;
int precisionCount = 0;
double recall = 0;
int recallCount = 0;
for (Result r : e.getValue()) {
if (r.getPrecision() != null) {
precision += r.getPrecision();
precisionCount++;
}
if (r.getRecall() != null) {
recall += r.getRecall();
recallCount++;
}
}
System.out.println("Precision count "+precisionCount);
System.out.println("Mean precision "+(precision / precisionCount));
System.out.println("Recall count "+recallCount);
System.out.println("Mean recall "+(recall / recallCount));
}
}
private static class Result {
private int totalOrig = 0;
private int totalExtr = 0;
private int success = 0;
public void addSuccess() {
success++;
}
public void addOrig(int totalorig) {
this.totalOrig += totalorig;
}
public void addExtr(int totalextr) {
this.totalExtr += totalextr;
}
public Double getPrecision() {
return (totalExtr == 0) ? null : (double) success / totalExtr;
}
public Double getRecall() {
return (totalOrig == 0) ? null : (double) success / totalOrig;
}
@Override
public String toString() {
return "Result{" + "totalOrig=" + totalOrig + ", totalExtr=" + totalExtr + ", success=" + success + '}';
}
}
}
| 7,963 | 37.288462 | 137 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/SVMInitialClassificationEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation;
import java.io.IOException;
import java.util.List;
import libsvm.svm_parameter;
import org.apache.commons.cli.ParseException;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.structure.SVMInitialZoneClassifier;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.structure.model.BxZoneLabel;
import pl.edu.icm.cermine.tools.BxDocUtils.DocumentsIterator;
import pl.edu.icm.cermine.tools.classification.general.BxDocsToTrainingSamplesConverter;
import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder;
import pl.edu.icm.cermine.tools.classification.general.PenaltyCalculator;
import pl.edu.icm.cermine.tools.classification.general.TrainingSample;
import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class SVMInitialClassificationEvaluator extends CrossvalidatingZoneClassificationEvaluator {
@Override
protected SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree) throws IOException, AnalysisException, CloneNotSupportedException {
for (TrainingSample<BxZoneLabel> trainingSample : trainingSamples) {
trainingSample.setLabel(trainingSample.getLabel().getGeneralLabel());
}
PenaltyCalculator pc = new PenaltyCalculator(trainingSamples);
int[] intClasses = new int[pc.getClasses().size()];
double[] classesWeights = new double[pc.getClasses().size()];
int labelIdx = 0;
for (BxZoneLabel label : pc.getClasses()) {
intClasses[labelIdx] = label.ordinal();
classesWeights[labelIdx] = pc.getPenaltyWeigth(label);
++labelIdx;
}
SVMZoneClassifier zoneClassifier = new SVMZoneClassifier(SVMInitialZoneClassifier.getFeatureVectorBuilder());
svm_parameter param = SVMZoneClassifier.getDefaultParam();
param.svm_type = svm_parameter.C_SVC;
param.gamma = gamma;
param.C = C;
System.out.println(degree);
param.degree = degree;
param.kernel_type = kernelType;
param.weight = classesWeights;
param.weight_label = intClasses;
zoneClassifier.setParameter(param);
zoneClassifier.buildClassifier(trainingSamples);
return zoneClassifier;
}
public static void main(String[] args)
throws ParseException, AnalysisException, IOException, TransformationException, CloneNotSupportedException {
CrossvalidatingZoneClassificationEvaluator.main(args, new SVMInitialClassificationEvaluator());
}
@Override
protected FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder() {
return SVMInitialZoneClassifier.getFeatureVectorBuilder();
}
@Override
public List<TrainingSample<BxZoneLabel>> getSamples(String inputFile, String ext) throws AnalysisException {
DocumentsIterator it = new DocumentsIterator(inputFile, ext);
return BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(),
getFeatureVectorBuilder(),
BxZoneLabel.getLabelToGeneralMap());
}
}
| 4,121 | 42.389474 | 220 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/SVMBodyClassificationEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation;
import java.io.IOException;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import libsvm.svm_parameter;
import org.apache.commons.cli.ParseException;
import pl.edu.icm.cermine.content.filtering.ContentFilterTools;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.structure.model.BxZoneLabel;
import pl.edu.icm.cermine.structure.model.BxZoneLabelCategory;
import pl.edu.icm.cermine.tools.BxDocUtils.DocumentsIterator;
import pl.edu.icm.cermine.tools.classification.general.*;
import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class SVMBodyClassificationEvaluator extends CrossvalidatingZoneClassificationEvaluator {
@Override
protected SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree)
throws IOException, AnalysisException, CloneNotSupportedException {
PenaltyCalculator pc = new PenaltyCalculator(trainingSamples);
int[] intClasses = new int[pc.getClasses().size()];
double[] classesWeights = new double[pc.getClasses().size()];
int labelIdx = 0;
for (BxZoneLabel label : pc.getClasses()) {
intClasses[labelIdx] = label.ordinal();
classesWeights[labelIdx] = pc.getPenaltyWeigth(label);
++labelIdx;
}
SVMZoneClassifier zoneClassifier = new SVMZoneClassifier(getFeatureVectorBuilder());
svm_parameter param = SVMZoneClassifier.getDefaultParam();
param.svm_type = svm_parameter.C_SVC;
param.gamma = gamma;
param.C = C;
System.out.println(degree);
param.degree = degree;
param.kernel_type = kernelType;
param.weight = classesWeights;
param.weight_label = intClasses;
zoneClassifier.setParameter(param);
zoneClassifier.buildClassifier(trainingSamples);
return zoneClassifier;
}
public static void main(String[] args)
throws ParseException, AnalysisException, IOException, TransformationException, CloneNotSupportedException {
CrossvalidatingZoneClassificationEvaluator.main(args, new SVMBodyClassificationEvaluator());
}
@Override
protected FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder() {
return ContentFilterTools.VECTOR_BUILDER;
}
@Override
public List<TrainingSample<BxZoneLabel>> getSamples(String inputFile, String ext) throws AnalysisException {
Map<BxZoneLabel, BxZoneLabel> map = new EnumMap<BxZoneLabel, BxZoneLabel>(BxZoneLabel.class);
map.put(BxZoneLabel.BODY_ACKNOWLEDGMENT, BxZoneLabel.BODY_CONTENT);
map.put(BxZoneLabel.BODY_CONFLICT_STMT, BxZoneLabel.BODY_CONTENT);
map.put(BxZoneLabel.BODY_EQUATION, BxZoneLabel.BODY_JUNK);
map.put(BxZoneLabel.BODY_FIGURE, BxZoneLabel.BODY_JUNK);
map.put(BxZoneLabel.BODY_GLOSSARY, BxZoneLabel.BODY_JUNK);
map.put(BxZoneLabel.BODY_TABLE, BxZoneLabel.BODY_JUNK);
DocumentsIterator it = new DocumentsIterator(inputFile, ext);
List<TrainingSample<BxZoneLabel>> samples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(),
getFeatureVectorBuilder(), map);
List<TrainingSample<BxZoneLabel>> tss = ClassificationUtils.filterElements(samples, BxZoneLabelCategory.CAT_BODY);
return tss;
}
}
| 4,423 | 41.951456 | 152 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/ReferenceTokenClassificationEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.JDOMException;
import org.xml.sax.InputSource;
import pl.edu.icm.cermine.bibref.CRFBibReferenceParser;
import pl.edu.icm.cermine.bibref.parsing.model.Citation;
import pl.edu.icm.cermine.bibref.parsing.tools.NlmCitationExtractor;
import pl.edu.icm.cermine.exception.AnalysisException;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ReferenceTokenClassificationEvaluator {
public static void main(String[] args) throws JDOMException, IOException, AnalysisException {
if (args.length != 3) {
System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>");
System.exit(1);
}
int foldness = Integer.parseInt(args[0]);
String modelPathSuffix = args[1];
String testPathSuffix = args[2];
Map<String, Map<String, Integer>> origToTest = new HashMap<String, Map<String, Integer>>();
Map<String, Map<String, Integer>> testToOrig = new HashMap<String, Map<String, Integer>>();
for (int i = 0; i < foldness; i++) {
System.out.println("Fold "+i);
String modelPath = modelPathSuffix + i;
String termsPath = modelPathSuffix + "terms" + i;
String journalsPath = modelPathSuffix + "journals" + i;
String surnamesPath = modelPathSuffix + "surnames" + i;
String institutionsPath = modelPathSuffix + "institutions" + i;
CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath, termsPath, journalsPath, surnamesPath, institutionsPath);
String testPath = testPathSuffix + i;
File testFile = new File(testPath);
List<Citation> testCitations;
InputStream testIS = null;
try {
testIS = new FileInputStream(testFile);
InputSource testSource = new InputSource(testIS);
testCitations = NlmCitationExtractor.extractCitations(testSource);
} finally {
if (testIS != null) {
testIS.close();
}
}
System.out.println(testCitations.size());
for (Citation orig : testCitations) {
Citation test = parser.parseToTokenList(orig.getText());
assert(test.getTokens().size() == orig.getTokens().size());
for (int j = 0; j < test.getTokens().size(); j++) {
String origLabel = orig.getTokens().get(j).getLabel().name();
String testLabel = test.getTokens().get(j).getLabel().name();
if (origToTest.get(origLabel) == null) {
origToTest.put(origLabel, new HashMap<String, Integer>());
}
if (origToTest.get(origLabel).get(testLabel) == null) {
origToTest.get(origLabel).put(testLabel, 0);
}
origToTest.get(origLabel).put(testLabel, origToTest.get(origLabel).get(testLabel)+1);
if (testToOrig.get(testLabel) == null) {
testToOrig.put(testLabel, new HashMap<String, Integer>());
}
if (testToOrig.get(testLabel).get(origLabel) == null) {
testToOrig.get(testLabel).put(origLabel, 0);
}
testToOrig.get(testLabel).put(origLabel, testToOrig.get(testLabel).get(origLabel)+1);
}
}
}
String[] labels = new String[]{"GIVENNAME", "SURNAME", "ARTICLE_TITLE",
"SOURCE", "VOLUME", "ISSUE", "YEAR", "PAGEF",
"PAGEL", "TEXT"};
double meanPrecision = 0;
double meanRecall = 0;
double meanFScore = 0;
for (String orig : labels) {
System.out.println("Original "+orig);
System.out.println(origToTest.get(orig));
for (String test : labels) {
if (origToTest.get(orig).get(test) == null) {
System.out.print("0 ");
} else {
System.out.print(origToTest.get(orig).get(test) + " ");
}
}
System.out.println("");
int total = 0;
for (int val : testToOrig.get(orig).values()) {
total += val;
}
double precision = (double)origToTest.get(orig).get(orig) / total;
System.out.println("Precision: " + precision);
meanPrecision += precision;
total = 0;
for (int val : origToTest.get(orig).values()) {
total += val;
}
double recall = (double)origToTest.get(orig).get(orig) / total;
System.out.println("Recall: " + recall);
meanRecall += recall;
double fScore = 2*precision*recall/(precision+recall);
System.out.println("F-Score: " + fScore);
meanFScore += fScore;
System.out.println("");
}
meanPrecision /= labels.length;
meanRecall /= labels.length;
meanFScore /= labels.length;
System.out.println("Mean precision " + meanPrecision);
System.out.println("Mean recall " + meanRecall);
System.out.println("Mean f-score " + meanFScore);
}
}
| 6,536 | 40.636943 | 137 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/SVMMetadataClassificationEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import libsvm.svm_parameter;
import org.apache.commons.cli.ParseException;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.structure.SVMMetadataZoneClassifier;
import pl.edu.icm.cermine.structure.model.BxPage;
import pl.edu.icm.cermine.structure.model.BxZone;
import pl.edu.icm.cermine.structure.model.BxZoneLabel;
import pl.edu.icm.cermine.structure.model.BxZoneLabelCategory;
import pl.edu.icm.cermine.tools.BxDocUtils.DocumentsIterator;
import pl.edu.icm.cermine.tools.classification.general.*;
import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class SVMMetadataClassificationEvaluator extends CrossvalidatingZoneClassificationEvaluator {
@Override
protected SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree)
throws IOException, AnalysisException, CloneNotSupportedException {
Map<BxZoneLabel, BxZoneLabel> labelMapper = BxZoneLabel.getLabelToGeneralMap();
for (TrainingSample<BxZoneLabel> sample : trainingSamples) {
if (sample.getLabel().getCategory() != BxZoneLabelCategory.CAT_METADATA) {
sample.setLabel(labelMapper.get(sample.getLabel()));
}
}
PenaltyCalculator pc = new PenaltyCalculator(trainingSamples);
int[] intClasses = new int[pc.getClasses().size()];
double[] classesWeights = new double[pc.getClasses().size()];
int labelIdx = 0;
for (BxZoneLabel label : pc.getClasses()) {
intClasses[labelIdx] = label.ordinal();
classesWeights[labelIdx] = pc.getPenaltyWeigth(label);
++labelIdx;
}
SVMZoneClassifier zoneClassifier = new SVMZoneClassifier(SVMMetadataZoneClassifier.getFeatureVectorBuilder());
svm_parameter param = SVMZoneClassifier.getDefaultParam();
param.svm_type = svm_parameter.C_SVC;
param.gamma = gamma;
param.C = C;
System.out.println(degree);
param.degree = degree;
param.kernel_type = kernelType;
param.weight = classesWeights;
param.weight_label = intClasses;
zoneClassifier.setParameter(param);
zoneClassifier.buildClassifier(trainingSamples);
return zoneClassifier;
}
public static void main(String[] args)
throws ParseException, AnalysisException, IOException, TransformationException, CloneNotSupportedException {
CrossvalidatingZoneClassificationEvaluator.main(args, new SVMMetadataClassificationEvaluator());
}
@Override
protected FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder() {
return SVMMetadataZoneClassifier.getFeatureVectorBuilder();
}
@Override
public List<TrainingSample<BxZoneLabel>> getSamples(String inputFile, String ext) throws AnalysisException {
DocumentsIterator it = new DocumentsIterator(inputFile, ext);
List<TrainingSample<BxZoneLabel>> samples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(),
getFeatureVectorBuilder(), null);
return ClassificationUtils.filterElements(samples, BxZoneLabelCategory.CAT_METADATA);
}
}
| 4,220 | 41.636364 | 152 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/SegmentationEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation;
import com.google.common.collect.Lists;
import java.io.*;
import java.util.*;
import org.apache.commons.io.FileUtils;
import pl.edu.icm.cermine.exception.AnalysisException;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.structure.DocstrumSegmenter;
import pl.edu.icm.cermine.structure.DocumentSegmenter;
import pl.edu.icm.cermine.structure.HierarchicalReadingOrderResolver;
import pl.edu.icm.cermine.structure.ReadingOrderResolver;
import pl.edu.icm.cermine.structure.model.*;
import pl.edu.icm.cermine.structure.tools.BxModelUtils;
import pl.edu.icm.cermine.structure.tools.UnsegmentedPagesFlattener;
import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter;
import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader;
/**
* @author Krzysztof Rusek
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class SegmentationEvaluator {
private DocumentSegmenter pageSegmenter = new DocstrumSegmenter();
private final Set<BxZoneLabel> ignoredLabels = EnumSet.noneOf(BxZoneLabel.class);
private final UnsegmentedPagesFlattener flattener = new UnsegmentedPagesFlattener();
private final ReadingOrderResolver resolver = new HierarchicalReadingOrderResolver();
private final TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader();
private final BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter();
public void setPageSegmenter(DocumentSegmenter pageSegmenter) {
this.pageSegmenter = pageSegmenter;
}
public void setIgnoredLabels(Collection<BxZoneLabel> labels) {
ignoredLabels.clear();
ignoredLabels.addAll(labels);
}
public void setLabels(Collection<BxZoneLabel> labels) {
ignoredLabels.addAll(EnumSet.allOf(BxZoneLabel.class));
ignoredLabels.removeAll(labels);
}
protected void preprocessDocument(BxDocument document) {
flattener.process(document);
}
protected BxDocument processDocument(BxDocument document) throws AnalysisException {
return pageSegmenter.segmentDocument(document);
}
private void printSeparator() {
System.out.print(" +----------+");
Results.printSeparator();
}
protected void printDocumentStart() {
System.out.print(" | Page |");
Results.printLevelHeader();
System.out.print(" | |");
Results.printColumnHeader();
printSeparator();
}
protected void printItemResults(BxDocument expected, BxDocument actual, int idx, Results results) {
printItemResults(idx, results);
}
protected void printItemResults(int pageIndex, Results results) {
Formatter formatter = new Formatter(System.out, Locale.US);
formatter.format(" | %8d |", pageIndex + 1);
results.printResults(formatter);
}
protected void printDocumentResults(Results results) {
printSeparator();
Formatter formatter = new Formatter(System.out, Locale.US);
formatter.format(" | Total: |");
results.printResults(formatter);
}
protected void printFinalResults(Results results) {
results.printSummary();
}
private LevelResults compareWords(BxPage expected, BxPage actual) {
Map<BxChunk, BxWord> map = BxModelUtils.mapChunksToWords(actual);
LevelResults results = new LevelResults();
for (BxZone expectedZone : expected) {
if (ignoredLabels.contains(expectedZone.getLabel())) {
continue;
}
for (BxLine expectedLine : expectedZone) {
for (BxWord expectedWord : expectedLine) {
Set<BxWord> actualWords = new HashSet<BxWord>();
for (BxChunk chunk : expectedWord) {
actualWords.add(map.get(chunk));
}
if (actualWords.size() == 1) {
for (BxWord actualWord : actualWords) {
if (actualWord.childrenCount() == expectedWord.childrenCount()) {
results.matched++;
}
}
}
results.all++;
}
}
}
return results;
}
private LevelResults compareLines(BxPage expected, BxPage actual) {
Map<BxChunk, BxLine> map = BxModelUtils.mapChunksToLines(actual);
LevelResults results = new LevelResults();
for (BxZone expectedZone : expected) {
if (ignoredLabels.contains(expectedZone.getLabel())) {
continue;
}
for (BxLine expectedLine : expectedZone) {
Set<BxLine> actualLines = new HashSet<BxLine>();
for (BxWord word : expectedLine) {
for (BxChunk chunk : word) {
actualLines.add(map.get(chunk));
}
}
if (actualLines.size() == 1) {
for (BxLine actualLine : actualLines) {
if (BxModelUtils.countChunks(actualLine) == BxModelUtils.countChunks(expectedLine)) {
results.matched++;
}
}
}
results.all++;
}
}
return results;
}
private LevelResults compareZones(BxPage expected, BxPage actual) {
Map<BxChunk, BxZone> map = BxModelUtils.mapChunksToZones(actual);
LevelResults results = new LevelResults();
for (BxZone expectedZone : expected) {
if (ignoredLabels.contains(expectedZone.getLabel())) {
continue;
}
Set<BxZone> actualZones = new HashSet<BxZone>();
for (BxLine line : expectedZone) {
for (BxWord word : line) {
for (BxChunk chunk : word) {
actualZones.add(map.get(chunk));
}
}
}
if (actualZones.size() == 1) {
for (BxZone actualZone : actualZones) {
if (BxModelUtils.countChunks(actualZone) == BxModelUtils.countChunks(expectedZone)) {
results.matched++;
}
}
}
results.all++;
}
return results;
}
protected Results compareItems(BxDocument expected, BxDocument actual) {
Results results = new Results();
for (int i = 0; i < expected.childrenCount(); i++) {
BxPage expPage = expected.getChild(i);
BxPage actPage = actual.getChild(i);
results.zoneLevel.add(compareZones(expPage, actPage));
results.lineLevel.add(compareLines(expPage, actPage));
results.wordLevel.add(compareWords(expPage, actPage));
}
return results;
}
protected BxDocument prepareActualDocument(BxDocument document) throws AnalysisException {
document = BxModelUtils.deepClone(document);
preprocessDocument(document);
return processDocument(document);
}
protected BxDocument prepareExpectedDocument(BxDocument document) throws AnalysisException {
resolver.resolve(document);
return document;
}
protected BxDocument readDocument(Reader input) throws TransformationException {
return new BxDocument().setPages(reader.read(input));
}
protected void writeDocument(BxDocument document, Writer output) throws TransformationException {
writer.write(output, Lists.newArrayList(document));
}
public static class Results {
private LevelResults zoneLevel = new LevelResults();
private LevelResults lineLevel = new LevelResults();
private LevelResults wordLevel = new LevelResults();
public void add(Results results) {
zoneLevel.add(results.zoneLevel);
lineLevel.add(results.lineLevel);
wordLevel.add(results.wordLevel);
}
public void printResults(Formatter formatter) {
zoneLevel.printResults(formatter);
lineLevel.printResults(formatter);
wordLevel.printResults(formatter);
formatter.format("%n");
}
public static void printLevelHeader() {
System.out.print(" Zones |");
System.out.print(" Lines |");
System.out.print(" Words |");
System.out.println();
}
public static void printColumnHeader() {
LevelResults.printHeader();
LevelResults.printHeader();
LevelResults.printHeader();
System.out.println();
}
public static void printSeparator() {
LevelResults.printSeparator();
LevelResults.printSeparator();
LevelResults.printSeparator();
System.out.println();
}
public void printSummary() {
Formatter formatter = new Formatter(System.out, Locale.US);
System.out.println(" * zones");
zoneLevel.printSummary(formatter);
System.out.println(" * lines");
lineLevel.printSummary(formatter);
System.out.println(" * words");
wordLevel.printSummary(formatter);
}
}
public static class LevelResults {
private int all = 0;
private int matched = 0;
public void add(LevelResults results) {
all += results.all;
matched += results.matched;
}
public void printResults(Formatter formatter) {
formatter.format(" %8d %8d %7.2f%% |",
all, matched, getScore() * 100);
}
public static void printHeader() {
System.out.print(" All Matched Score |");
}
public static void printSeparator() {
System.out.print("----------------------------------------------+");
}
public void printSummary(Formatter formatter) {
formatter.format(" * all : %8d%n", all);
formatter.format(" * matched : %8d%n", matched);
formatter.format(" * score : %7.2f%%%n", getScore() * 100);
}
public double getScore() {
if (all == 0) {
return 1.0;
} else {
return ((double) matched) / all;
}
}
}
public static void main(String[] args) throws AnalysisException, IOException, TransformationException {
SegmentationEvaluator evaluator = new SegmentationEvaluator();
evaluator.ignoredLabels.add(BxZoneLabel.BODY_TABLE);
evaluator.ignoredLabels.add(BxZoneLabel.BODY_FIGURE);
evaluator.ignoredLabels.add(BxZoneLabel.BODY_EQUATION);
File file = new File(args[0]);
Collection<File> files = FileUtils.listFiles(file, new String[]{"xml"}, true);
Results results = new Results();
int i = 0;
double zoneScores = 0;
double lineScores = 0;
double wordScores = 0;
BxDocument origDoc;
BxDocument testDoc;
Reader reader;
for (File filee : files) {
System.out.println(new Date(System.currentTimeMillis()));
System.out.println(filee.getName());
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filee), "UTF-8"));
origDoc = evaluator.prepareExpectedDocument(evaluator.readDocument(reader));
testDoc = evaluator.prepareActualDocument(origDoc);
Results docRes = evaluator.compareItems(origDoc, testDoc);
results.add(docRes);
zoneScores += results.zoneLevel.getScore();
lineScores += results.lineLevel.getScore();
wordScores += results.wordLevel.getScore();
System.out.println(++i);
}
zoneScores /= i;
lineScores /= i;
wordScores /= i;
System.out.println("Documents: " + i);
System.out.println("Average zone score: " + zoneScores);
System.out.println("Average line score: " + lineScores);
System.out.println("Average word score: " + wordScores);
results.printSummary();
}
}
| 13,238 | 35.67313 | 109 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/NlmIterator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import java.io.File;
import java.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class NlmIterator implements Iterable<NlmPair> {
private int curItemIdx = -1;
private List<NlmPair> entries = null;
private String originalNlmExtension;
private final Comparator<File> alphabeticalOrder = new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
String baseName1 = FilenameUtils.getBaseName(o1.getName());
String extension1 = FilenameUtils.getExtension(o1.getName());
String baseName2 = FilenameUtils.getBaseName(o2.getName());
if (o1.getPath().equals(o2.getPath())) {
return 0;
}
if (o1.getParent().equals(o2.getParent())
&& baseName1.equals(baseName2)) {
return extension1.equals(originalNlmExtension) ? -1 : 1;
}
return o1.getPath().compareTo(o2.getPath());
}
};
public NlmIterator(String dirPath) {
this(dirPath, "nxml", "metaxml");
}
public NlmIterator(String dirPath, final String originalNlmExtension, final String extractedNlmExtension) {
this.originalNlmExtension = originalNlmExtension;
File dir = new File(dirPath);
if (!dir.exists()) {
throw new IllegalArgumentException("provided input file must exist");
}
if (!dir.isDirectory()) {
throw new IllegalArgumentException("provided input file must be a directory");
}
if (dir.list().length == 0) {
throw new IllegalArgumentException("provided directory can't be empty");
}
List<File> interestingFiles = new ArrayList<File>(FileUtils.listFiles(dir, new String[]{originalNlmExtension, extractedNlmExtension}, true));
if (interestingFiles.size() < 2) {
throw new IllegalArgumentException("There are too few files in the given directory!");
}
Collections.sort(interestingFiles, alphabeticalOrder);
entries = new ArrayList<NlmPair>();
int i = 0;
while (i < interestingFiles.size() - 1) {
File file = interestingFiles.get(i);
File nextFile = interestingFiles.get(i + 1);
String name = file.getName();
String nextName = nextFile.getName();
if (FilenameUtils.getBaseName(name).equals(FilenameUtils.getBaseName(nextName))
&& !FilenameUtils.getExtension(name).equals(FilenameUtils.getExtension(nextName))) {
entries.add(new NlmPair(file, nextFile));
i += 2;
} else {
i++;
}
}
}
public int size() {
return entries.size();
}
@Override
public Iterator<NlmPair> iterator() {
return new Iterator<NlmPair>() {
@Override
public boolean hasNext() {
return curItemIdx + 1 < entries.size();
}
@Override
public NlmPair next() {
curItemIdx++;
if (curItemIdx >= entries.size()) {
throw new NoSuchElementException();
}
NlmPair actualItem = entries.get(curItemIdx);
return actualItem;
}
@Override
public void remove() {
++curItemIdx;
}
};
}
}
| 4,329 | 32.828125 | 149 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/ClassificationResults.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import java.util.*;
import pl.edu.icm.cermine.metadata.zoneclassification.tools.LabelPair;
import pl.edu.icm.cermine.structure.model.BxZoneLabel;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ClassificationResults {
private final Set<BxZoneLabel> possibleLabels;
private final Map<LabelPair, Integer> classificationMatrix;
private int goodRecognitions = 0;
private int badRecognitions = 0;
public ClassificationResults() {
possibleLabels = EnumSet.noneOf(BxZoneLabel.class);
classificationMatrix = new HashMap<LabelPair, Integer>();
}
private void addPossibleLabel(BxZoneLabel lab) {
if (!possibleLabels.contains(lab)) {
for (BxZoneLabel lab2 : possibleLabels) {
classificationMatrix.put(new LabelPair(lab, lab2), 0);
classificationMatrix.put(new LabelPair(lab2, lab), 0);
}
classificationMatrix.put(new LabelPair(lab, lab), 0);
possibleLabels.add(lab);
}
}
public Set<BxZoneLabel> getPossibleLabels() {
return possibleLabels;
}
public void addOneZoneResult(BxZoneLabel label1, BxZoneLabel label2) {
addPossibleLabel(label1);
addPossibleLabel(label2);
LabelPair coord = new LabelPair(label1, label2);
classificationMatrix.put(coord, classificationMatrix.get(coord) + 1);
if (label1.equals(label2)) {
goodRecognitions++;
} else {
badRecognitions++;
}
}
public void add(ClassificationResults results) {
for (BxZoneLabel possibleLabel : results.getPossibleLabels()) {
addPossibleLabel(possibleLabel);
}
for (BxZoneLabel label1 : results.possibleLabels) {
for (BxZoneLabel label2 : results.possibleLabels) {
LabelPair coord = new LabelPair(label1, label2);
classificationMatrix.put(coord, classificationMatrix.get(coord) + results.classificationMatrix.get(coord));
}
}
goodRecognitions += results.goodRecognitions;
badRecognitions += results.badRecognitions;
}
public double sum(Collection<Double> collection) {
double sum = 0.0;
for (Double elem : collection) {
sum += elem;
}
return sum;
}
public void printQualityMeasures() {
double accuracy;
int correctly = 0;
int all = 0;
final double EPS = 0.00001;
for (BxZoneLabel label : possibleLabels) {
LabelPair positiveCoord = new LabelPair(label, label);
correctly += classificationMatrix.get(positiveCoord);
for (BxZoneLabel label1 : possibleLabels) {
LabelPair traversingCoord = new LabelPair(label, label1);
all += classificationMatrix.get(traversingCoord);
}
}
accuracy = (double) correctly / (double) all;
Formatter formatter = new Formatter(System.out, Locale.US);
formatter.format("Accuracy = %2.2f%n", accuracy * 100.0);
Map<BxZoneLabel, Double> precisions = new EnumMap<BxZoneLabel, Double>(BxZoneLabel.class);
int pairsInvolved = 0;
for (BxZoneLabel predictedClass : possibleLabels) {
int correctPredictions = 0;
int allPredictions = 0;
for (BxZoneLabel realClass : possibleLabels) {
if (realClass.equals(predictedClass)) {
correctPredictions = classificationMatrix.get(new LabelPair(realClass, predictedClass));
}
allPredictions += classificationMatrix.get(new LabelPair(realClass, predictedClass));
}
double precision = (double) correctPredictions / allPredictions;
precisions.put(predictedClass, precision);
if (precision > EPS) {
++pairsInvolved;
}
formatter.format(predictedClass + " precision = %2.2f\n", precision * 100.0);
}
double precision = sum(precisions.values());
precision /= pairsInvolved;
formatter.format("Precision = %2.2f%n", precision * 100.0);
Map<BxZoneLabel, Double> recalls = new EnumMap<BxZoneLabel, Double>(BxZoneLabel.class);
pairsInvolved = 0;
for (BxZoneLabel realClass : possibleLabels) {
int correctPredictions = 0;
int predictions = 0;
for (BxZoneLabel predictedClass : possibleLabels) {
if (realClass.equals(predictedClass)) {
correctPredictions = classificationMatrix.get(new LabelPair(realClass, predictedClass));
}
predictions += classificationMatrix.get(new LabelPair(realClass, predictedClass));
}
double recall = (double) correctPredictions / predictions;
recalls.put(realClass, recall);
if (recall > EPS) {
++pairsInvolved;
}
formatter.format(realClass + " recall = %2.2f\n", recall * 100.0);
}
double recall = sum(recalls.values());
recall /= pairsInvolved;
formatter.format("Recall = %2.2f%n", recall * 100.0);
}
public void printMatrix() {
int maxLabelLength = 0;
Map<BxZoneLabel, Integer> labelLengths = new EnumMap<BxZoneLabel, Integer>(BxZoneLabel.class);
for (BxZoneLabel label : possibleLabels) {
int labelLength = label.toString().length();
if (labelLength > maxLabelLength) {
maxLabelLength = labelLength;
}
labelLengths.put(label, labelLength);
}
StringBuilder oneLine = new StringBuilder();
oneLine.append("+-").append(new String(new char[maxLabelLength]).replace('\0', '-')).append("-+");
for (BxZoneLabel label : possibleLabels) {
oneLine.append(new String(new char[labelLengths.get(label) + 2]).replace('\0', '-'));
oneLine.append("+");
}
System.out.println(oneLine);
oneLine = new StringBuilder();
oneLine.append("| ").append(new String(new char[maxLabelLength]).replace('\0', ' ')).append(" |");
for (BxZoneLabel label : possibleLabels) {
oneLine.append(' ').append(label).append(" |");
}
System.out.println(oneLine);
oneLine = new StringBuilder();
oneLine.append("+-").append(new String(new char[maxLabelLength]).replace('\0', '-')).append("-+");
for (BxZoneLabel label : possibleLabels) {
oneLine.append(new String(new char[labelLengths.get(label) + 2]).replace('\0', '-'));
oneLine.append("+");
}
System.out.println(oneLine);
for (BxZoneLabel label1 : possibleLabels) {
oneLine = new StringBuilder();
oneLine.append("| ").append(label1);
oneLine.append(new String(new char[maxLabelLength - labelLengths.get(label1)]).replace('\0', ' '));
oneLine.append(" |");
for (BxZoneLabel label2 : possibleLabels) {
LabelPair coord = new LabelPair(label1, label2);
String nbRecognitions = classificationMatrix.get(coord).toString();
oneLine.append(" ").append(nbRecognitions);
oneLine.append(new String(new char[Math.max(0, labelLengths.get(label2) - nbRecognitions.length() + 1)]).replace('\0', ' '));
oneLine.append("|");
}
System.out.println(oneLine);
}
oneLine = new StringBuilder();
oneLine.append("+-").append(new String(new char[maxLabelLength]).replace('\0', '-')).append("-+");
for (BxZoneLabel label : possibleLabels) {
oneLine.append(new String(new char[labelLengths.get(label) + 2]).replace('\0', '-'));
oneLine.append("+");
}
System.out.println(oneLine);
System.out.println();
}
public void printShortSummary() {
int allRecognitions = goodRecognitions + badRecognitions;
System.out.print("Good recognitions: " + goodRecognitions + "/" + allRecognitions);
if (allRecognitions > 0) {
System.out.format(" (%.1f%%)%n", 100.0 * goodRecognitions / allRecognitions);
}
System.out.print("Bad recognitions: " + badRecognitions + "/" + allRecognitions);
if (allRecognitions > 0) {
System.out.format(" (%.1f%%)%n", 100.0 * badRecognitions / allRecognitions);
}
}
public void printLongSummary() {
int maxLabelLength = 0;
for (BxZoneLabel label : possibleLabels) {
int labelLength = label.toString().length();
if (labelLength > maxLabelLength) {
maxLabelLength = labelLength;
}
}
System.out.println("Good recognitions per zone type:");
for (BxZoneLabel label1 : possibleLabels) {
String spaces;
int labelGoodRecognitions = 0;
int labelAllRecognitions = 0;
for (BxZoneLabel label2 : possibleLabels) {
LabelPair coord = new LabelPair(label1, label2);
if (label1.equals(label2)) {
labelGoodRecognitions += classificationMatrix.get(coord);
}
labelAllRecognitions += classificationMatrix.get(coord);
}
spaces = new String(new char[maxLabelLength - label1.toString().length() + 1]).replace('\0', ' ');
System.out.format("%s:%s%d/%d", label1, spaces, labelGoodRecognitions, labelAllRecognitions);
if (labelAllRecognitions > 0) {
System.out.format(" (%.1f%%)", 100.0 * labelGoodRecognitions / labelAllRecognitions);
}
System.out.println();
}
System.out.println();
}
public double getMeanF1Score() {
Map<BxZoneLabel, Double> precisions = new EnumMap<BxZoneLabel, Double>(BxZoneLabel.class);
for (BxZoneLabel predictedClass : possibleLabels) {
int correctPredictions = 0;
int allPredictions = 0;
for (BxZoneLabel realClass : possibleLabels) {
if (realClass.equals(predictedClass)) {
correctPredictions = classificationMatrix.get(new LabelPair(realClass, predictedClass));
}
allPredictions += classificationMatrix.get(new LabelPair(realClass, predictedClass));
}
double precision = (double) correctPredictions / allPredictions;
if (allPredictions == 0) {
precision = 1;
}
precisions.put(predictedClass, precision);
}
Map<BxZoneLabel, Double> recalls = new EnumMap<BxZoneLabel, Double>(BxZoneLabel.class);
for (BxZoneLabel realClass : possibleLabels) {
int correctPredictions = 0;
int predictions = 0;
for (BxZoneLabel predictedClass : possibleLabels) {
if (realClass.equals(predictedClass)) {
correctPredictions = classificationMatrix.get(new LabelPair(realClass, predictedClass));
}
predictions += classificationMatrix.get(new LabelPair(realClass, predictedClass));
}
double recall = (double) correctPredictions / predictions;
if (predictions == 0) {
recall = 1;
}
recalls.put(realClass, recall);
}
double f1score = 0;
for (BxZoneLabel l : possibleLabels) {
double f1 = 2 * precisions.get(l) * recalls.get(l) / (precisions.get(l) + recalls.get(l));
System.out.println("F1 " + l + " " + f1);
f1score += f1;
}
f1score /= possibleLabels.size();
System.out.println("Mean F1 " + f1score);
return f1score;
}
}
| 12,676 | 40.563934 | 141 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/DocumentSetResult.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class DocumentSetResult {
private final List<EvalInformationType> evalTypes;
private final Map<String, Map<EvalInformationType, SingleInformationDocResult>> results;
private final Map<EvalInformationType, Double> precision = new EnumMap<EvalInformationType, Double>(EvalInformationType.class);
private final Map<EvalInformationType, Double> recall = new EnumMap<EvalInformationType, Double>(EvalInformationType.class);
private final Map<EvalInformationType, Double> f1 = new EnumMap<EvalInformationType, Double>(EvalInformationType.class);
public DocumentSetResult(List<EvalInformationType> types) {
this.evalTypes = types;
results = new HashMap<String, Map<EvalInformationType, SingleInformationDocResult>>();
}
public void addResult(String doc, SingleInformationDocResult result) {
if (results.get(doc) == null) {
results.put(doc, new EnumMap<EvalInformationType, SingleInformationDocResult>(EvalInformationType.class));
}
results.get(doc).put(result.getType(), result);
}
public void evaluate() {
precision.clear();
recall.clear();
f1.clear();
Map<EvalInformationType, Integer> precisionCount = new EnumMap<EvalInformationType, Integer>(EvalInformationType.class);
Map<EvalInformationType, Integer> recallCount = new EnumMap<EvalInformationType, Integer>(EvalInformationType.class);
Map<EvalInformationType, Integer> f1Count = new EnumMap<EvalInformationType, Integer>(EvalInformationType.class);
for (EvalInformationType type: evalTypes) {
precision.put(type, 0.);
recall.put(type, 0.);
f1.put(type, 0.);
precisionCount.put(type, 0);
recallCount.put(type, 0);
f1Count.put(type, 0);
}
for (Map.Entry<String, Map<EvalInformationType, SingleInformationDocResult>> result: results.entrySet()) {
for (EvalInformationType type: evalTypes) {
SingleInformationDocResult sResult = result.getValue().get(type);
if (sResult == null) {
throw new IllegalArgumentException("Document " + result.getKey() + " does not contain result for " + type);
}
if (sResult.getPrecision() != null) {
precision.put(type, precision.get(type) + sResult.getPrecision());
precisionCount.put(type, precisionCount.get(type) + 1);
}
if (sResult.getRecall() != null) {
recall.put(type, recall.get(type) + sResult.getRecall());
recallCount.put(type, recallCount.get(type) + 1);
}
if (sResult.getF1() != null) {
f1.put(type, f1.get(type) + sResult.getF1());
f1Count.put(type, f1Count.get(type) + 1);
}
}
}
for (EvalInformationType type: evalTypes) {
precision.put(type, precision.get(type)/precisionCount.get(type));
recall.put(type, recall.get(type)/recallCount.get(type));
f1.put(type, f1.get(type)/f1Count.get(type));
}
}
public void printTotalSummary() {
double avgPrecision = 0;
for (Double prec: precision.values()) {
avgPrecision += prec;
}
avgPrecision /= evalTypes.size();
double avgRecall = 0;
for (Double rec: recall.values()) {
avgRecall += rec;
}
avgRecall /= evalTypes.size();
double avgF1 = 0;
for (Double f: f1.values()) {
avgF1 += f;
}
avgF1 /= evalTypes.size();
System.out.printf("Average precision\t\t%4.2f%n", 100 * avgPrecision);
System.out.printf("Average recall\t\t%4.2f%n", 100 * avgRecall);
System.out.printf("Average F1 score\t\t%4.2f%n", 100 * avgF1);
}
public void printTypeSummary(EvalInformationType type) {
System.out.printf(type + ": precision: %4.2f" + ", recall: %4.2f" + ", F1: %4.2f\n\n",
getPrecision(type) == null ? -1. : 100 * getPrecision(type),
getRecall(type) == null ? -1. : 100 * getRecall(type),
getF1(type) == null ? -1. : 100 * getF1(type));
}
public void printDocument(String doc, int i) {
Map<EvalInformationType, SingleInformationDocResult> docResults = results.get(doc);
System.out.println("");
System.out.println(">>>>>>>>> "+i);
System.out.println(doc);
for (EvalInformationType type: evalTypes) {
System.out.println("");
System.out.println(type);
docResults.get(type).prettyPrint();
}
System.out.println("");
}
public void printCSV(String doc) {
Map<EvalInformationType, SingleInformationDocResult> docResults = results.get(doc);
System.out.print(doc);
for (EvalInformationType type: evalTypes) {
System.out.print(",");
docResults.get(type).printCSV();
}
System.out.println("");
}
public Double getF1(EvalInformationType type) {
return f1.get(type);
}
public Double getPrecision(EvalInformationType type) {
return precision.get(type);
}
public Double getRecall(EvalInformationType type) {
return recall.get(type);
}
}
| 6,439 | 39.25 | 131 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/ListInformationResult.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ListInformationResult implements SingleInformationDocResult<List<String>> {
private EvalInformationType type;
private List<String> expectedValue;
private List<String> extractedValue;
private Double precision;
private Double recall;
private Comparator<String> comp = EvaluationUtils.defaultComparator;
public ListInformationResult(EvalInformationType type, List<String> expectedValue,
List<String> extractedValue) {
this(type, EvaluationUtils.defaultComparator, expectedValue, extractedValue);
}
public ListInformationResult(EvalInformationType type, Comparator<String> comp,
List<String> expectedValue, List<String> extractedValue) {
this.expectedValue = expectedValue;
this.extractedValue = extractedValue;
this.type = type;
this.comp = comp;
}
@Override
public boolean hasExpected() {
return expectedValue != null && !expectedValue.isEmpty();
}
@Override
public boolean hasExtracted() {
return extractedValue != null && !extractedValue.isEmpty();
}
@Override
public Double getPrecision() {
if (!hasExtracted()) {
return null;
}
if (precision != null) {
return precision;
}
int correct = 0;
List<String> tmp = new ArrayList<String>(expectedValue);
external:
for (String partExt : extractedValue) {
for (String partExp : tmp) {
if (comp.compare(partExp, partExt) == 0) {
++correct;
tmp.remove(partExp);
continue external;
}
}
}
precision = (double) correct / extractedValue.size();
return precision;
}
@Override
public Double getRecall() {
if (!hasExpected()) {
return null;
}
if (recall != null) {
return recall;
}
int correct = 0;
List<String> tmp = new ArrayList<String>(expectedValue);
external:
for (String partExt : extractedValue) {
internal:
for (String partExp : tmp) {
if (comp.compare(partExp, partExt) == 0) {
++correct;
tmp.remove(partExp);
continue external;
}
}
}
recall = (double) correct / expectedValue.size();
return recall;
}
@Override
public Double getF1() {
if (getPrecision() == null && getRecall() == null) {
return null;
}
if (getPrecision() == null || getRecall() == null || getPrecision() + getRecall() == 0) {
return 0.;
}
return 2*getPrecision()*getRecall()/(getPrecision()+getRecall());
}
@Override
public List<String> getExpected() {
return expectedValue;
}
@Override
public void setExpected(List<String> expectedValue) {
this.expectedValue = expectedValue;
}
@Override
public List<String> getExtracted() {
return extractedValue;
}
@Override
public void setExtracted(List<String> extractedValue) {
this.extractedValue = extractedValue;
}
public void print(int mode, String name) {
if (mode == 0) {
System.out.println("");
System.out.println("Expected " + name + ":");
for (String expected : expectedValue) {
System.out.println(" " + expected);
}
System.out.println("Extracted " + name + ":");
for (String extracted : extractedValue) {
System.out.println(" " + extracted);
}
System.out.printf("Precision: %4.2f%n", getPrecision());
System.out.printf("Recall: %4.2f%n", getRecall());
}
if (mode == 1) {
if (!hasExtracted() && !hasExpected()) {
System.out.print("null");
} else if (!hasExtracted() || !hasExpected()) {
System.out.print("0");
} else {
System.out.print(getF1());
}
System.out.print(",");
}
}
@Override
public EvalInformationType getType() {
return type;
}
@Override
public void prettyPrint() {
System.out.println("Expected " + type + ":");
for (String expected : expectedValue) {
System.out.println(" " + expected);
}
System.out.println("Extracted " + type + ":");
for (String extracted : extractedValue) {
System.out.println(" " + extracted);
}
System.out.printf("Precision: %4.2f%n", getPrecision());
System.out.printf("Recall: %4.2f%n", getRecall());
}
@Override
public void printCSV() {
if (!hasExtracted() && !hasExpected()) {
System.out.print("NA");
} else if (!hasExtracted() || !hasExpected()) {
System.out.print("0");
} else {
System.out.print(getF1());
}
}
}
| 6,105 | 29.227723 | 97 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/SingleInformationDocResult.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
* @param <T> result type
*/
public interface SingleInformationDocResult<T> {
EvalInformationType getType();
boolean hasExpected();
boolean hasExtracted();
T getExpected();
T getExtracted();
void setExpected(T expected);
void setExtracted(T extracted);
Double getPrecision();
Double getRecall();
Double getF1();
void prettyPrint();
void printCSV();
}
| 1,279 | 23.615385 | 78 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/EvalInformationType.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public enum EvalInformationType {
TITLE,
ABSTRACT,
KEYWORDS,
AUTHORS,
AFFILIATIONS,
AUTHOR_AFFILIATIONS,
EMAILS,
AUTHOR_EMAILS,
JOURNAL,
VOLUME,
ISSUE,
PAGES,
YEAR,
DOI,
HEADERS,
HEADER_LEVELS,
REFERENCES
}
| 1,202 | 19.05 | 78 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/EvaluationUtils.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang.StringUtils;
import pl.edu.icm.cermine.tools.TextUtils;
import pl.edu.icm.cermine.tools.distance.CosineDistance;
import pl.edu.icm.cermine.tools.distance.SmithWatermanDistance;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class EvaluationUtils {
public static double compareStringsSW(String expectedText, String extractedText) {
List<String> expectedTokens = TextUtils.tokenize(expectedText.trim());
List<String> extractedTokens = TextUtils.tokenize(extractedText.trim());
SmithWatermanDistance distanceFunc = new SmithWatermanDistance(.0, .0);
double distance = distanceFunc.compare(expectedTokens, extractedTokens);
return 2 * distance / (double) (expectedTokens.size() + extractedTokens.size());
}
public static List<String> removeLeadingZerosFromDate(List<String> strings) {
List<String> ret = new ArrayList<String>();
for (String string : strings) {
String[] parts = string.split("\\s");
if (parts.length > 1) {
List<String> newDate = new ArrayList<String>();
for (String part : parts) {
newDate.add(part.replaceFirst("^0+(?!$)", ""));
}
ret.add(StringUtils.join(newDate, " "));
} else {
ret.add(string);
}
}
return ret;
}
public static boolean isSubsequence(String str, String sub) {
if (sub.isEmpty()) {
return true;
}
if (str.isEmpty()) {
return false;
}
if (str.charAt(0) == sub.charAt(0)) {
return isSubsequence(str.substring(1), sub.substring(1));
}
return isSubsequence(str.substring(1), sub);
}
public static final Comparator<String> defaultComparator = new Comparator<String>() {
@Override
public int compare(String t1, String t2) {
return t1.trim().replaceAll(" +", " ").compareToIgnoreCase(t2.trim().replaceAll(" +", " "));
}
};
public static Comparator<String> cosineComparator() {
return cosineComparator(0.7);
}
public static Comparator<String> cosineComparator(final double threshold) {
return new Comparator<String>() {
@Override
public int compare(String t1, String t2) {
if (new CosineDistance().compare(TextUtils.tokenize(t1), TextUtils.tokenize(t2)) > threshold) {
return 0;
}
return t1.compareToIgnoreCase(t2);
}
};
}
public static final Comparator<String> swComparator = new Comparator<String>() {
@Override
public int compare(String t1, String t2) {
String t1Norm = t1.replaceAll("[^a-zA-Z]", "");
String t2Norm = t2.replaceAll("[^a-zA-Z]", "");
if (compareStringsSW(t1, t2) >= .9
|| (!t1Norm.isEmpty() && t1Norm.equals(t2Norm))) {
return 0;
}
return t1.compareToIgnoreCase(t2);
}
};
public static final Comparator<String> authorComparator = new Comparator<String>() {
@Override
public int compare(String t1, String t2) {
if (t1.toLowerCase(Locale.ENGLISH).replaceAll("[^a-z]", "").equals(t2.toLowerCase(Locale.ENGLISH).replaceAll("[^a-z]", ""))) {
return 0;
}
return t1.trim().compareToIgnoreCase(t2.trim());
}
};
public static final Comparator<String> emailComparator = new Comparator<String>() {
@Override
public int compare(String t1, String t2) {
String t1Norm = t1.toLowerCase(Locale.ENGLISH).replaceAll("[^a-z0-9@]", "").replaceFirst("^e.?mail:? *", "");
String t2Norm = t1.toLowerCase(Locale.ENGLISH).replaceAll("[^a-z0-9@]", "").replaceFirst("^e.?mail:? *", "");
if (t1Norm.equals(t2Norm)) {
return 0;
}
return t1.trim().compareToIgnoreCase(t2.trim());
}
};
public static final Comparator<String> journalComparator = new Comparator<String>() {
@Override
public int compare(String t1, String t2) {
if (EvaluationUtils.isSubsequence(t1.toLowerCase(Locale.ENGLISH).replaceAll("[^a-z]", ""), t2.toLowerCase(Locale.ENGLISH).replaceAll("[^a-z]", ""))) {
return 0;
}
return t1.trim().compareToIgnoreCase(t2.trim());
}
};
public static Comparator<String> headerComparator(final Comparator<String> comp) {
return new Comparator<String>() {
@Override
public int compare(String t1, String t2) {
List<String> t1Lines = Lists.newArrayList(t1.split("\n"));
List<String> t2Lines = Lists.newArrayList(t2.split("\n"));
if (t1Lines.size() != t2Lines.size()) {
return -1;
}
for (int i = 0; i < t1Lines.size(); i++) {
if (t1Lines.get(i).equals(t2Lines.get(i))) {
continue;
}
String trimmed1 = t1Lines.get(i).trim();
String trimmed2 = t2Lines.get(i).trim();
if (t1Lines.get(i).length() - trimmed1.length() != t2Lines.get(i).length() - trimmed2.length()) {
return -1;
}
if (comp.compare(trimmed1, trimmed2) != 0) {
return -1;
}
}
return 0;
}
};
}
}
| 6,616 | 36.384181 | 162 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/NlmPair.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import java.io.File;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class NlmPair {
private File originalNlm;
private File extractedNlm;
public NlmPair(File originalNlm, File extractedNlm) {
this.originalNlm = originalNlm;
this.extractedNlm = extractedNlm;
}
public File getOriginalNlm() {
return originalNlm;
}
public void setOriginalNlm(File originalNlm) {
this.originalNlm = originalNlm;
}
public File getExtractedNlm() {
return extractedNlm;
}
public void setExtractedNlm(File extractedNlm) {
this.extractedNlm = extractedNlm;
}
}
| 1,440 | 26.711538 | 78 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/DividedEvaluationSet.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import pl.edu.icm.cermine.structure.model.BxZoneLabel;
import pl.edu.icm.cermine.tools.classification.general.TrainingSample;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class DividedEvaluationSet {
public DividedEvaluationSet(List<TrainingSample<BxZoneLabel>> trainingSamples, List<TrainingSample<BxZoneLabel>> testSamples) {
this.trainingSamples = trainingSamples;
this.testSamples = testSamples;
}
List<TrainingSample<BxZoneLabel>> trainingSamples;
List<TrainingSample<BxZoneLabel>> testSamples;
public List<TrainingSample<BxZoneLabel>> getTrainingDocuments() {
return trainingSamples;
}
public List<TrainingSample<BxZoneLabel>> getTestDocuments() {
return testSamples;
}
public static List<DividedEvaluationSet> build(List<TrainingSample<BxZoneLabel>> samples, int numberOfFolds) {
List<TrainingSample<BxZoneLabel>> shuffledDocs = new ArrayList<TrainingSample<BxZoneLabel>>(samples.size());
shuffledDocs.addAll(samples);
Random random = new Random(2102);
Collections.shuffle(shuffledDocs, random);
List<List<TrainingSample<BxZoneLabel>>> dividedSamples = new ArrayList<List<TrainingSample<BxZoneLabel>>>(numberOfFolds);
for (int fold = 0; fold < numberOfFolds; ++fold) {
int docsPerSet = shuffledDocs.size() / (numberOfFolds - fold);
dividedSamples.add(new ArrayList<TrainingSample<BxZoneLabel>>());
for (int idx = 0; idx < docsPerSet; ++idx) {
dividedSamples.get(dividedSamples.size() - 1).add(shuffledDocs.get(0));
shuffledDocs.remove(0);
}
}
List<DividedEvaluationSet> ret = new ArrayList<DividedEvaluationSet>(numberOfFolds);
for (int fold = 0; fold < numberOfFolds; ++fold) {
List<TrainingSample<BxZoneLabel>> trainingSamples = new ArrayList<TrainingSample<BxZoneLabel>>();
List<TrainingSample<BxZoneLabel>> testSamples = new ArrayList<TrainingSample<BxZoneLabel>>();
for (int setIdx = 0; setIdx < numberOfFolds; ++setIdx) {
if (setIdx == fold) {
testSamples.addAll(dividedSamples.get(setIdx));
} else {
trainingSamples.addAll(dividedSamples.get(setIdx));
}
}
ret.add(new DividedEvaluationSet(trainingSamples, testSamples));
}
return ret;
}
} | 3,359 | 40.481481 | 131 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/SimpleInformationResult.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import java.util.Comparator;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class SimpleInformationResult implements SingleInformationDocResult<String> {
private EvalInformationType type;
private String expectedValue;
private String extractedValue;
private Boolean correct;
private Comparator<String> comp;
public SimpleInformationResult(EvalInformationType type, String expectedValue, String extractedValue) {
this(type, EvaluationUtils.defaultComparator, expectedValue, extractedValue);
}
public SimpleInformationResult(EvalInformationType type, Comparator<String> comp, String expectedValue, String extractedValue) {
this.expectedValue = expectedValue;
this.extractedValue = extractedValue;
this.correct = null;
this.type = type;
this.comp = comp;
}
private boolean isCorrect() {
if (correct != null) {
return correct;
}
correct = hasExpected() && hasExtracted() && comp.compare(expectedValue, extractedValue) == 0;
return correct;
}
@Override
public boolean hasExpected() {
return expectedValue != null && !expectedValue.isEmpty();
}
@Override
public boolean hasExtracted() {
return extractedValue != null && !extractedValue.isEmpty();
}
@Override
public String getExpected() {
return expectedValue;
}
@Override
public void setExpected(String expectedValue) {
this.expectedValue = expectedValue;
}
@Override
public String getExtracted() {
return extractedValue;
}
@Override
public void setExtracted(String extractedValue) {
this.extractedValue = extractedValue;
}
@Override
public Double getPrecision() {
if (!hasExtracted()) {
return null;
}
return isCorrect() ? 1. : 0.;
}
@Override
public Double getRecall() {
if (!hasExpected()) {
return null;
}
return isCorrect() ? 1. : 0.;
}
@Override
public Double getF1() {
if (getPrecision() == null && getRecall() == null) {
return null;
}
if (getPrecision() == null || getRecall() == null || getPrecision() + getRecall() == 0) {
return 0.;
}
return 2*getPrecision()*getRecall()/(getPrecision()+getRecall());
}
@Override
public EvalInformationType getType() {
return type;
}
@Override
public void prettyPrint() {
System.out.println("Expected " + type + ": " + expectedValue);
System.out.println("Extracted " + type + ": " + extractedValue);
System.out.println("Correct: " + (isCorrect() ? "yes" : "no"));
}
@Override
public void printCSV() {
if (!hasExtracted() && !hasExpected()) {
System.out.print("NA");
} else if (!hasExtracted() || !hasExpected()) {
System.out.print("0");
} else {
System.out.print(getF1());
}
}
}
| 3,862 | 27.404412 | 132 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/DateComparator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import java.util.List;
import pl.edu.icm.cermine.tools.TextUtils;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class DateComparator {
public static boolean yearsMatch(List<String> expected, List<String> extracted) {
for (String expectedDate : expected) {
List<String> expectedParts = TextUtils.tokenize(expectedDate);
String expectedYear = null;
for (String part : expectedParts) {
if (TextUtils.isNumberBetween(part, 1900, 2100)) {
expectedYear = part;
break;
}
}
if (expectedYear == null) {
return false;
} else {
String extractedYear = null;
for (String extractedDate : extracted) {
List<String> extractedParts = TextUtils.tokenize(extractedDate);
for (String part : extractedParts) {
if (part.length() == 4 && part.matches("^[0-9]+$")
&& Integer.parseInt(part) < 2100 && Integer.parseInt(part) > 1900) {
extractedYear = part;
break;
}
}
if (extractedYear != null && extractedYear.equals(expectedYear)) {
return true;
}
}
}
}
return false;
}
}
| 2,265 | 36.147541 | 100 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/tools/RelationInformationResult.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.tools;
import java.util.*;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class RelationInformationResult implements SingleInformationDocResult<Set<RelationInformationResult.StringRelation>> {
private EvalInformationType type;
private Set<StringRelation> expectedValue;
private Set<StringRelation> extractedValue;
private Double precision;
private Double recall;
private Comparator<String> comp1;
private Comparator<String> comp2;
public RelationInformationResult(EvalInformationType type, Set<StringRelation> expected, Set<StringRelation> extracted) {
this(type, EvaluationUtils.defaultComparator, EvaluationUtils.defaultComparator,
expected, extracted);
}
public RelationInformationResult(EvalInformationType type, Comparator<String> comp1,
Comparator<String> comp2, Set<StringRelation> expected, Set<StringRelation> extracted) {
this.type = type;
this.comp1 = comp1;
this.comp2 = comp2;
this.expectedValue = expected;
this.extractedValue = extracted;
}
@Override
public boolean hasExpected() {
return expectedValue != null && !expectedValue.isEmpty();
}
@Override
public boolean hasExtracted() {
return extractedValue != null && !extractedValue.isEmpty();
}
@Override
public Double getPrecision() {
if (!hasExtracted()) {
return null;
}
if (precision != null) {
return precision;
}
int correct = 0;
List<StringRelation> tmp = new ArrayList<StringRelation>(expectedValue);
external:
for (StringRelation partExt : extractedValue) {
for (StringRelation partExp : tmp) {
if (comp1.compare(partExt.element1, partExp.element1) == 0
&& comp2.compare(partExt.element2, partExp.element2) == 0) {
++correct;
tmp.remove(partExp);
continue external;
}
}
}
precision = (double) correct / extractedValue.size();
return precision;
}
@Override
public Double getRecall() {
if (!hasExpected()) {
return null;
}
if (recall != null) {
return recall;
}
int correct = 0;
List<StringRelation> tmp = new ArrayList<StringRelation>(expectedValue);
external:
for (StringRelation partExt : extractedValue) {
internal:
for (StringRelation partExp : tmp) {
if (comp1.compare(partExt.element1, partExp.element1) == 0
&& comp2.compare(partExt.element2, partExp.element2) == 0) {
++correct;
tmp.remove(partExp);
continue external;
}
}
}
recall = (double) correct / expectedValue.size();
return recall;
}
@Override
public Double getF1() {
if (getPrecision() == null && getRecall() == null) {
return null;
}
if (getPrecision() == null || getRecall() == null || getPrecision() + getRecall() == 0) {
return 0.;
}
return 2*getPrecision()*getRecall()/(getPrecision()+getRecall());
}
@Override
public EvalInformationType getType() {
return type;
}
@Override
public void prettyPrint() {
System.out.println("");
System.out.println("Expected " + type + ":");
for (StringRelation expected : expectedValue) {
System.out.println(" " + expected);
}
System.out.println("Extracted " + type + ":");
for (StringRelation extracted : extractedValue) {
System.out.println(" " + extracted);
}
System.out.printf("Precision: %4.2f%n", getPrecision());
System.out.printf("Recall: %4.2f%n", getRecall());
}
@Override
public void printCSV() {
if (!hasExtracted() && !hasExpected()) {
System.out.print("NA");
} else if (!hasExtracted() || !hasExpected()) {
System.out.print("0");
} else {
System.out.print(getF1());
}
}
@Override
public void setExpected(Set<StringRelation> expected) {
this.expectedValue = expected;
}
@Override
public void setExtracted(Set<StringRelation> extracted) {
this.extractedValue = extracted;
}
@Override
public Set<StringRelation> getExpected() {
return expectedValue;
}
@Override
public Set<StringRelation> getExtracted() {
return extractedValue;
}
public static class StringRelation {
private String element1;
private String element2;
public StringRelation(String element1, String element2) {
this.element1 = element1;
this.element2 = element2;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final StringRelation other = (StringRelation) obj;
if ((this.element1 == null) ? (other.element1 != null) : !this.element1.equals(other.element1)) {
return false;
}
return (this.element2 == null) ? (other.element2 == null) : this.element2.equals(other.element2);
}
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + (this.element1 != null ? this.element1.hashCode() : 0);
hash = 67 * hash + (this.element2 != null ? this.element2.hashCode() : 0);
return hash;
}
@Override
public String toString() {
return element1 + " --- " + element2;
}
}
} | 6,758 | 30.584112 | 125 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/exception/EvaluationException.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.exception;
/**
* Thrown when an unrecoverable problem occurs during evaluation.
*
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class EvaluationException extends Exception {
private static final long serialVersionUID = 7601197515845834554L;
public EvaluationException() {
super();
}
public EvaluationException(String message, Throwable cause) {
super(message, cause);
}
public EvaluationException(String message) {
super(message);
}
public EvaluationException(Throwable cause) {
super(cause);
}
}
| 1,363 | 29.311111 | 78 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/PdfExtractNlmEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.NLMToDocumentReader;
import pl.edu.icm.cermine.evaluation.transformers.PdfExtractToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class PdfExtractNlmEvaluator extends SystemEvaluator {
private final NLMToDocumentReader origReader = new NLMToDocumentReader();
private final PdfExtractToDocumentReader testReader = new PdfExtractToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return origReader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return testReader;
}
public static void main(String[] args) throws EvaluationException {
PdfExtractNlmEvaluator e = new PdfExtractNlmEvaluator();
e.process(args);
}
}
| 2,077 | 34.220339 | 93 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/GrobidBwmetaEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.BwmetaToDocumentReader;
import pl.edu.icm.cermine.evaluation.transformers.GrobidToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class GrobidBwmetaEvaluator extends SystemEvaluator {
private final BwmetaToDocumentReader origReader = new BwmetaToDocumentReader();
private final GrobidToDocumentReader testReader = new GrobidToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.ABSTRACT,
EvalInformationType.KEYWORDS, EvalInformationType.AUTHORS, EvalInformationType.AFFILIATIONS,
EvalInformationType.AUTHOR_AFFILIATIONS, EvalInformationType.EMAILS, EvalInformationType.AUTHOR_EMAILS,
EvalInformationType.JOURNAL, EvalInformationType.VOLUME, EvalInformationType.ISSUE,
EvalInformationType.PAGES, EvalInformationType.YEAR, EvalInformationType.DOI,
EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return origReader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return testReader;
}
public static void main(String[] args) throws EvaluationException {
GrobidBwmetaEvaluator e = new GrobidBwmetaEvaluator();
e.process(args);
}
}
| 2,518 | 37.166667 | 115 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/ParscitNlmEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.NLMToDocumentReader;
import pl.edu.icm.cermine.evaluation.transformers.ParscitToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ParscitNlmEvaluator extends SystemEvaluator {
private final NLMToDocumentReader origReader = new NLMToDocumentReader();
private final ParscitToDocumentReader testReader = new ParscitToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.ABSTRACT,
EvalInformationType.AUTHORS, EvalInformationType.AFFILIATIONS, EvalInformationType.EMAILS,
EvalInformationType.HEADERS, EvalInformationType.HEADER_LEVELS, EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return origReader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return testReader;
}
public static void main(String[] args) throws EvaluationException {
ParscitNlmEvaluator e = new ParscitNlmEvaluator();
e.process(args);
}
}
| 2,268 | 36.196721 | 108 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/PdfxNlmEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.NLMToDocumentReader;
import pl.edu.icm.cermine.evaluation.transformers.PdfxToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class PdfxNlmEvaluator extends SystemEvaluator {
private final NLMToDocumentReader origReader = new NLMToDocumentReader();
private final PdfxToDocumentReader testReader = new PdfxToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.ABSTRACT,
EvalInformationType.EMAILS, EvalInformationType.DOI,
EvalInformationType.HEADERS, EvalInformationType.HEADER_LEVELS, EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return origReader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return testReader;
}
public static void main(String[] args) throws EvaluationException {
PdfxNlmEvaluator e = new PdfxNlmEvaluator();
e.process(args);
}
}
| 2,216 | 35.344262 | 108 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/SystemEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import pl.edu.icm.cermine.evaluation.tools.EvaluationUtils;
import pl.edu.icm.cermine.evaluation.tools.NlmPair;
import pl.edu.icm.cermine.evaluation.tools.NlmIterator;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import pl.edu.icm.cermine.bibref.model.BibEntry;
import pl.edu.icm.cermine.content.model.DocumentSection;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.RelationInformationResult.StringRelation;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.metadata.model.DateType;
import pl.edu.icm.cermine.metadata.model.DocumentAffiliation;
import pl.edu.icm.cermine.metadata.model.DocumentAuthor;
import pl.edu.icm.cermine.metadata.model.IDType;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public abstract class SystemEvaluator {
protected abstract List<EvalInformationType> getTypes();
protected abstract FormatToModelReader<Document> getOrigReader();
protected abstract FormatToModelReader<Document> getExtrReader();
protected Document getOriginal(NlmPair pair) throws EvaluationException {
try {
return getOrigReader().read(new BufferedReader(
new InputStreamReader(new FileInputStream(pair.getOriginalNlm()), "UTF-8")));
} catch (TransformationException ex) {
throw new EvaluationException(ex);
} catch (FileNotFoundException ex) {
throw new EvaluationException(ex);
} catch (UnsupportedEncodingException ex) {
throw new EvaluationException(ex);
}
}
protected Document getExtracted(NlmPair pair) throws EvaluationException {
try {
return getExtrReader().read(new BufferedReader(
new InputStreamReader(new FileInputStream(pair.getExtractedNlm()), "UTF-8")));
} catch (TransformationException ex) {
throw new EvaluationException(ex);
} catch (FileNotFoundException ex) {
throw new EvaluationException(ex);
} catch (UnsupportedEncodingException ex) {
throw new EvaluationException(ex);
}
}
public DocumentSetResult evaluate(int mode, NlmIterator files) throws EvaluationException {
DocumentSetResult results = new DocumentSetResult(getTypes());
if (mode == 1) {
System.out.println("path," + StringUtils.join(getTypes(), ","));
}
int i = 0;
for (NlmPair pair : files) {
i++;
String file = pair.getOriginalNlm().getPath();
Document origDoc = getOriginal(pair);
Document testDoc = getExtracted(pair);
for (EvalInformationType type: getTypes()) {
switch (type) {
case TITLE:
results.addResult(file, new SimpleInformationResult(type,
EvaluationUtils.swComparator,
origDoc.getMetadata().getTitle(),
testDoc.getMetadata().getTitle()));
break;
case ABSTRACT:
results.addResult(file, new SimpleInformationResult(type,
EvaluationUtils.swComparator,
origDoc.getMetadata().getAbstrakt(),
testDoc.getMetadata().getAbstrakt()));
break;
case KEYWORDS:
results.addResult(file, new ListInformationResult(type,
origDoc.getMetadata().getKeywords(),
testDoc.getMetadata().getKeywords()));
break;
case AUTHORS:
List<String> authorOrig = new ArrayList<String>();
for (DocumentAuthor author: origDoc.getMetadata().getAuthors()) {
authorOrig.add(author.getName());
}
List<String> authorTest = new ArrayList<String>();
for (DocumentAuthor author: testDoc.getMetadata().getAuthors()) {
authorTest.add(author.getName());
}
results.addResult(file, new ListInformationResult(type,
EvaluationUtils.authorComparator,
authorOrig, authorTest));
break;
case AFFILIATIONS:
List<String> affOrig = new ArrayList<String>();
for (DocumentAffiliation aff: origDoc.getMetadata().getAffiliations()) {
affOrig.add(aff.getRawText());
}
List<String> affTest = new ArrayList<String>();
for (DocumentAffiliation aff: testDoc.getMetadata().getAffiliations()) {
affTest.add(aff.getRawText());
}
results.addResult(file, new ListInformationResult(type,
EvaluationUtils.cosineComparator(),
affOrig, affTest));
break;
case AUTHOR_AFFILIATIONS:
Set<StringRelation> relOrig = new HashSet<StringRelation>();
for (DocumentAuthor author: origDoc.getMetadata().getAuthors()) {
for (DocumentAffiliation aff: author.getAffiliations()) {
relOrig.add(new StringRelation(author.getName(), aff.getRawText()));
}
}
Set<StringRelation> relTest = new HashSet<StringRelation>();
for (DocumentAuthor author: testDoc.getMetadata().getAuthors()) {
for (DocumentAffiliation aff: author.getAffiliations()) {
relTest.add(new StringRelation(author.getName(), aff.getRawText()));
}
}
results.addResult(file, new RelationInformationResult(type,
EvaluationUtils.authorComparator, EvaluationUtils.cosineComparator(),
relOrig, relTest));
break;
case EMAILS:
results.addResult(file, new ListInformationResult(type,
EvaluationUtils.emailComparator,
origDoc.getMetadata().getEmails(),
testDoc.getMetadata().getEmails()));
break;
case AUTHOR_EMAILS:
Set<StringRelation> emailsOrig = new HashSet<StringRelation>();
for (DocumentAuthor author: origDoc.getMetadata().getAuthors()) {
for (String email: author.getEmails()) {
emailsOrig.add(new StringRelation(author.getName(), email));
}
}
Set<StringRelation> emailsTest = new HashSet<StringRelation>();
for (DocumentAuthor author: testDoc.getMetadata().getAuthors()) {
for (String email: author.getEmails()) {
emailsTest.add(new StringRelation(author.getName(), email));
}
}
results.addResult(file, new RelationInformationResult(type,
EvaluationUtils.authorComparator, EvaluationUtils.emailComparator,
emailsOrig, emailsTest));
break;
case JOURNAL:
results.addResult(file, new SimpleInformationResult(type,
EvaluationUtils.journalComparator,
origDoc.getMetadata().getJournal(),
testDoc.getMetadata().getJournal()));
break;
case VOLUME:
results.addResult(file, new SimpleInformationResult(type,
origDoc.getMetadata().getVolume(),
testDoc.getMetadata().getVolume()));
break;
case ISSUE:
results.addResult(file, new SimpleInformationResult(type,
origDoc.getMetadata().getIssue(),
testDoc.getMetadata().getIssue()));
break;
case PAGES:
results.addResult(file, new SimpleInformationResult(type,
origDoc.getMetadata().getFirstPage() + "--" + origDoc.getMetadata().getLastPage(),
testDoc.getMetadata().getFirstPage() + "--" + testDoc.getMetadata().getLastPage()));
break;
case YEAR:
String origYear = null;
if (origDoc.getMetadata().getDate(DateType.PUBLISHED) != null) {
origYear = origDoc.getMetadata().getDate(DateType.PUBLISHED).getYear();
}
String testYear = null;
if (testDoc.getMetadata().getDate(DateType.PUBLISHED) != null) {
testYear = origDoc.getMetadata().getDate(DateType.PUBLISHED).getYear();
}
results.addResult(file, new SimpleInformationResult(type,
origYear, testYear));
break;
case DOI:
results.addResult(file, new SimpleInformationResult(type,
origDoc.getMetadata().getId(IDType.DOI),
testDoc.getMetadata().getId(IDType.DOI)));
break;
case HEADERS:
List<String> headerOrig = new ArrayList<String>();
for (DocumentSection section: origDoc.getContent().getSections(true)) {
headerOrig.add(section.getTitle());
}
List<String> headerTest = new ArrayList<String>();
for (DocumentSection section: testDoc.getContent().getSections(true)) {
headerTest.add(section.getTitle());
}
results.addResult(file, new ListInformationResult(type,
EvaluationUtils.swComparator,
headerOrig, headerTest));
break;
case HEADER_LEVELS:
Set<StringRelation> headersOrig = new HashSet<StringRelation>();
for (DocumentSection section: origDoc.getContent().getSections(true)) {
headersOrig.add(new StringRelation(
String.valueOf(section.getLevel()),
section.getTitle()));
}
Set<StringRelation> headersTest = new HashSet<StringRelation>();
for (DocumentSection section: testDoc.getContent().getSections(true)) {
headersTest.add(new StringRelation(
String.valueOf(section.getLevel()),
section.getTitle()));
}
results.addResult(file, new RelationInformationResult(type,
EvaluationUtils.defaultComparator, EvaluationUtils.swComparator,
headersOrig, headersTest));
break;
case REFERENCES:
List<String> origRefs = new ArrayList<String>();
for (BibEntry entry: origDoc.getReferences()) {
origRefs.add(entry.getText());
}
List<String> testRefs = new ArrayList<String>();
for (BibEntry entry: testDoc.getReferences()) {
testRefs.add(entry.getText());
}
results.addResult(file, new ListInformationResult(type,
EvaluationUtils.cosineComparator(.6),
origRefs, testRefs));
break;
}
}
if (mode == 1) {
results.printCSV(file);
} else if (mode == 0) {
results.printDocument(file, i);
}
}
results.evaluate();
if (mode != 1) {
System.out.println("==== Summary (" + files.size() + " docs)====");
for (EvalInformationType type: getTypes()) {
results.printTypeSummary(type);
}
results.printTotalSummary();
}
return results;
}
public void process(String[] args) throws EvaluationException {
if (args.length != 3 && args.length != 4) {
System.out.println("Usage: " + this.getClass().getSimpleName() + " <input dir> <orig extension> <extract extension> <mode>");
return;
}
String directory = args[0];
String origExt = args[1];
String extrExt = args[2];
int mode = 0;
if (args.length == 4 && args[3].equals("csv")) {
mode = 1;
}
if (args.length == 4 && args[3].equals("q")) {
mode = 2;
}
NlmIterator iter = new NlmIterator(directory, origExt, extrExt);
evaluate(mode, iter);
}
}
| 15,334 | 49.114379 | 137 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/CermineNlmEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.NLMToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class CermineNlmEvaluator extends SystemEvaluator {
private final NLMToDocumentReader reader = new NLMToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.ABSTRACT,
EvalInformationType.KEYWORDS, EvalInformationType.AUTHORS, EvalInformationType.AFFILIATIONS,
EvalInformationType.AUTHOR_AFFILIATIONS, EvalInformationType.EMAILS, EvalInformationType.AUTHOR_EMAILS,
EvalInformationType.JOURNAL, EvalInformationType.VOLUME, EvalInformationType.ISSUE,
EvalInformationType.PAGES, EvalInformationType.YEAR, EvalInformationType.DOI,
EvalInformationType.HEADERS, EvalInformationType.HEADER_LEVELS, EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return reader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return reader;
}
public static void main(String[] args) throws EvaluationException {
CermineNlmEvaluator e = new CermineNlmEvaluator();
e.process(args);
}
}
| 2,399 | 37.709677 | 115 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/PdfExtractBwmetaEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.BwmetaToDocumentReader;
import pl.edu.icm.cermine.evaluation.transformers.PdfExtractToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class PdfExtractBwmetaEvaluator extends SystemEvaluator {
private final BwmetaToDocumentReader origReader = new BwmetaToDocumentReader();
private final PdfExtractToDocumentReader testReader = new PdfExtractToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return origReader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return testReader;
}
public static void main(String[] args) throws EvaluationException {
PdfExtractBwmetaEvaluator e = new PdfExtractBwmetaEvaluator();
e.process(args);
}
}
| 2,093 | 34.491525 | 93 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/PdfxBwmetaEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.BwmetaToDocumentReader;
import pl.edu.icm.cermine.evaluation.transformers.PdfxToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class PdfxBwmetaEvaluator extends SystemEvaluator {
private final BwmetaToDocumentReader origReader = new BwmetaToDocumentReader();
private final PdfxToDocumentReader testReader = new PdfxToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.ABSTRACT,
EvalInformationType.EMAILS, EvalInformationType.DOI,
EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return origReader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return testReader;
}
public static void main(String[] args) throws EvaluationException {
PdfxBwmetaEvaluator e = new PdfxBwmetaEvaluator();
e.process(args);
}
}
| 2,166 | 34.52459 | 90 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/CermineBwmetaEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.BwmetaToDocumentReader;
import pl.edu.icm.cermine.evaluation.transformers.NLMToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class CermineBwmetaEvaluator extends SystemEvaluator {
private final BwmetaToDocumentReader origReader = new BwmetaToDocumentReader();
private final NLMToDocumentReader testReader = new NLMToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.ABSTRACT,
EvalInformationType.KEYWORDS, EvalInformationType.AUTHORS, EvalInformationType.AFFILIATIONS,
EvalInformationType.AUTHOR_AFFILIATIONS, EvalInformationType.EMAILS, EvalInformationType.AUTHOR_EMAILS,
EvalInformationType.JOURNAL, EvalInformationType.VOLUME, EvalInformationType.ISSUE,
EvalInformationType.PAGES, EvalInformationType.YEAR, EvalInformationType.DOI,
EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return origReader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return testReader;
}
public static void main(String[] args) throws EvaluationException {
CermineBwmetaEvaluator e = new CermineBwmetaEvaluator();
e.process(args);
}
}
| 2,514 | 38.296875 | 115 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/ParscitBwmetaEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.BwmetaToDocumentReader;
import pl.edu.icm.cermine.evaluation.transformers.ParscitToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ParscitBwmetaEvaluator extends SystemEvaluator {
private final BwmetaToDocumentReader origReader = new BwmetaToDocumentReader();
private final ParscitToDocumentReader testReader = new ParscitToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.ABSTRACT,
EvalInformationType.AUTHORS, EvalInformationType.AFFILIATIONS, EvalInformationType.EMAILS,
EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return origReader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return testReader;
}
public static void main(String[] args) throws EvaluationException {
ParscitBwmetaEvaluator e = new ParscitBwmetaEvaluator();
e.process(args);
}
}
| 2,221 | 34.83871 | 102 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/systems/GrobidNlmEvaluator.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.systems;
import com.google.common.collect.Lists;
import java.util.*;
import pl.edu.icm.cermine.evaluation.exception.EvaluationException;
import pl.edu.icm.cermine.evaluation.tools.*;
import pl.edu.icm.cermine.evaluation.transformers.GrobidToDocumentReader;
import pl.edu.icm.cermine.evaluation.transformers.NLMToDocumentReader;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class GrobidNlmEvaluator extends SystemEvaluator {
private final NLMToDocumentReader origReader = new NLMToDocumentReader();
private final GrobidToDocumentReader testReader = new GrobidToDocumentReader();
@Override
protected List<EvalInformationType> getTypes() {
return Lists.newArrayList(EvalInformationType.TITLE, EvalInformationType.ABSTRACT,
EvalInformationType.KEYWORDS, EvalInformationType.AUTHORS, EvalInformationType.AFFILIATIONS,
EvalInformationType.AUTHOR_AFFILIATIONS, EvalInformationType.EMAILS, EvalInformationType.AUTHOR_EMAILS,
EvalInformationType.JOURNAL, EvalInformationType.VOLUME, EvalInformationType.ISSUE,
EvalInformationType.PAGES, EvalInformationType.YEAR, EvalInformationType.DOI,
EvalInformationType.HEADERS, EvalInformationType.REFERENCES);
}
@Override
protected FormatToModelReader<Document> getOrigReader() {
return origReader;
}
@Override
protected FormatToModelReader<Document> getExtrReader() {
return testReader;
}
public static void main(String[] args) throws EvaluationException {
GrobidNlmEvaluator e = new GrobidNlmEvaluator();
e.process(args);
}
}
| 2,527 | 38.5 | 115 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/PdfxToMetadataConverter.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.transformers;
import java.util.List;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.metadata.model.DocumentMetadata;
import pl.edu.icm.cermine.metadata.model.IDType;
import pl.edu.icm.cermine.tools.XMLTools;
import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class PdfxToMetadataConverter implements ModelToModelConverter<Element, DocumentMetadata> {
@Override
public DocumentMetadata convert(Element source, Object... hints) throws TransformationException {
try {
DocumentMetadata metadata = new DocumentMetadata();
convertTitle(source, metadata);
convertAbstract(source, metadata);
convertDoi(source, metadata);
convertEmails(source, metadata);
return metadata;
} catch (JDOMException ex) {
throw new TransformationException(ex);
}
}
private void convertTitle(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance(".//article-title[@class='DoCO:Title']");
Element title = (Element)xpath.selectSingleNode(source);
if (title != null) {
metadata.setTitle(XMLTools.getTextContent(title));
}
}
private void convertAbstract(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance(".//abstract[@class='DoCO:Abstract']");
Element abstrakt = (Element)xpath.selectSingleNode(source);
if (abstrakt != null) {
metadata.setAbstrakt(XMLTools.getTextContent(abstrakt));
}
}
private void convertDoi(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("/pdfx/meta/doi");
Element doi = (Element)xpath.selectSingleNode(source);
if (doi != null) {
metadata.addId(IDType.DOI, XMLTools.getTextContent(doi));
}
}
private void convertEmails(Element source, DocumentMetadata metadata) throws JDOMException {
XPath xpath = XPath.newInstance("//email");
List emailElems = xpath.selectNodes(source);
for (Object emailElem: emailElems) {
Element email = (Element) emailElem;
metadata.addEmail(XMLTools.getTextContent(email));
}
}
@Override
public List<DocumentMetadata> convertAll(List<Element> source, Object... hints) throws TransformationException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| 3,506 | 37.538462 | 116 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/PdfxToContentConverter.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.transformers;
import java.util.List;
import org.jdom.Element;
import org.jdom.JDOMException;
import pl.edu.icm.cermine.content.model.ContentStructure;
import pl.edu.icm.cermine.content.model.DocumentSection;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.tools.XMLTools;
import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class PdfxToContentConverter implements ModelToModelConverter<Element, ContentStructure> {
@Override
public ContentStructure convert(Element source, Object... hints) throws TransformationException {
try {
ContentStructure struct = new ContentStructure();
if (source == null) {
return struct;
}
for (Object secElem : source.getChildren("section")) {
DocumentSection section = convertSection((Element)secElem, 1);
if (section != null) {
struct.addSection(section);
}
}
return struct;
} catch (JDOMException ex) {
throw new TransformationException(ex);
}
}
@Override
public List<ContentStructure> convertAll(List<Element> source, Object... hints) throws TransformationException {
throw new UnsupportedOperationException("Not supported yet.");
}
private DocumentSection convertSection(Element source, int level) throws JDOMException {
DocumentSection section = new DocumentSection();
section.setLevel(level);
Element title = (Element) source.getChild("h"+level);
if (title == null) {
return null;
}
section.setTitle(XMLTools.getTextContent(title));
for (Object secElem : source.getChildren("section")) {
DocumentSection subsection = convertSection((Element)secElem, level+1);
if (subsection != null) {
section.addSection(subsection);
}
}
return section;
}
}
| 2,900 | 34.814815 | 116 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/NLMToContentConverter.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.transformers;
import java.util.List;
import org.jdom.Element;
import org.jdom.JDOMException;
import pl.edu.icm.cermine.content.model.ContentStructure;
import pl.edu.icm.cermine.content.model.DocumentSection;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.tools.XMLTools;
import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class NLMToContentConverter implements ModelToModelConverter<Element, ContentStructure> {
@Override
public ContentStructure convert(Element source, Object... hints) throws TransformationException {
try {
ContentStructure struct = new ContentStructure();
if (source == null) {
return struct;
}
for (Object secElem : source.getChildren("sec")) {
DocumentSection section = convertSection((Element)secElem, 1);
if (section != null) {
struct.addSection(section);
}
}
return struct;
} catch (JDOMException ex) {
throw new TransformationException(ex);
}
}
@Override
public List<ContentStructure> convertAll(List<Element> source, Object... hints) throws TransformationException {
throw new UnsupportedOperationException("Not supported yet.");
}
private DocumentSection convertSection(Element source, int level) throws JDOMException {
DocumentSection section = new DocumentSection();
section.setLevel(level);
Element title = (Element) source.getChild("title");
if (title == null) {
return null;
}
section.setTitle(XMLTools.getTextContent(title));
for (Object secElem : source.getChildren("sec")) {
DocumentSection subsection = convertSection((Element)secElem, level+1);
if (subsection != null) {
section.addSection(subsection);
}
}
return section;
}
}
| 2,889 | 34.679012 | 116 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/ElementToBibEntryConverter.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.transformers;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Element;
import pl.edu.icm.cermine.bibref.model.BibEntry;
import pl.edu.icm.cermine.bibref.model.BibEntryType;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.tools.XMLTools;
import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter;
/**
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ElementToBibEntryConverter implements ModelToModelConverter<Element, BibEntry> {
@Override
public BibEntry convert(Element source, Object... hints) throws TransformationException {
BibEntry bibEntry = new BibEntry(BibEntryType.ARTICLE);
String text = XMLTools.getTextContent(source);
bibEntry.setText(text);
return bibEntry;
}
@Override
public List<BibEntry> convertAll(List<Element> source, Object... hints) throws TransformationException {
List<BibEntry> entries = new ArrayList<BibEntry>(source.size());
for (Element element : source) {
entries.add(convert(element, hints));
}
return entries;
}
}
| 1,928 | 34.722222 | 108 | java |
CERMINE | CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/ParscitToDocumentReader.java | /**
* This file is part of CERMINE project.
* Copyright (c) 2011-2018 ICM-UW
*
* CERMINE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CERMINE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CERMINE. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.cermine.evaluation.transformers;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import pl.edu.icm.cermine.bibref.model.BibEntry;
import pl.edu.icm.cermine.content.model.ContentStructure;
import pl.edu.icm.cermine.exception.TransformationException;
import pl.edu.icm.cermine.metadata.model.DocumentMetadata;
import pl.edu.icm.cermine.model.Document;
import pl.edu.icm.cermine.tools.transformers.FormatToModelReader;
import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter;
/**
* Reads DocumentContentStructure model from HTML format.
*
* @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl)
*/
public class ParscitToDocumentReader implements FormatToModelReader<Document> {
@Override
public Document read(String string, Object... hints) throws TransformationException {
return read(new StringReader(string), hints);
}
@Override
public Document read(Reader reader, Object... hints) throws TransformationException {
try {
ModelToModelConverter<Element, DocumentMetadata> metaConverter = new ParscitToMetadataConverter();
ModelToModelConverter<Element, ContentStructure> structConverter = new ParscitToContentConverter();
ModelToModelConverter<Element, BibEntry> refConverter = new ElementToBibEntryConverter();
Element root = getRoot(reader);
Document document = new Document();
XPath xpath = XPath.newInstance("/algorithms/algorithm[@name='ParsHed']");
Element parshed = (Element) xpath.selectSingleNode(root);
document.setMetadata(metaConverter.convert(parshed));
xpath = XPath.newInstance("/algorithms/algorithm[@name='SectLabel']/variant");
Element sectlabel = (Element) xpath.selectSingleNode(root);
document.setContent(structConverter.convert(sectlabel));
xpath = XPath.newInstance("/algorithms/algorithm[@name='ParsCit']//citationList/citation/rawString");
List nodes = xpath.selectNodes(root);
List<Element> refElems = new ArrayList<Element>();
for(Object node: nodes) {
refElems.add((Element) node);
}
document.setReferences(refConverter.convertAll(refElems));
return document;
} catch (JDOMException ex) {
throw new TransformationException(ex);
} catch (IOException ex) {
throw new TransformationException(ex);
}
}
private Element getRoot(Reader reader) throws JDOMException, IOException {
SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
builder.setValidation(false);
builder.setFeature("http://xml.org/sax/features/validation", false);
builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
org.jdom.Document dom = builder.build(reader);
return dom.getRootElement();
}
@Override
public List<Document> readAll(String string, Object... hints) throws TransformationException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Document> readAll(Reader reader, Object... hints) throws TransformationException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| 4,439 | 40.886792 | 113 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.