Here is my java solution:
import java.sql.*;
import java.util.*;
public class GoDistance
{
private Connection connection;
private GoDistance() {}
/** returns a map (go-id/distance) */
private Map<String,Integer> ancestors(String go) throws SQLException
{
Map<String,Integer> acn2distance=new HashMap<String,Integer>();
//put self
acn2distance.put(go,0);
PreparedStatement stmt=null;
ResultSet row=null;
try
{
//search all the parents
stmt=connection.prepareStatement(
"SELECT DISTINCT "+
" graph_path.distance,"+
" ancestor.acc "+
" FROM "+
" term "+
" INNER JOIN graph_path ON term.id=graph_path.term2_id) "+
" INNER JOIN term AS ancestor ON ancestor.id=graph_path.term1_id) "+
" WHERE term.acc=?"
);
stmt.setString(1,go);
row=stmt.executeQuery();
while(row.next())
{
int distance=row.getInt(1);
String acn=row.getString(2);
Integer prev=acn2distance.get(acn);
if(prev==null || prev>distance)
{
acn2distance.put(acn,distance);
}
}
return acn2distance;
}
finally
{
if(row!=null) row.close();
if(stmt!=null) stmt.close();
}
}
private void run(String go1,String go2) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
connection=DriverManager.getConnection(
"jdbc:mysql://mysql.ebi.ac.uk:4085/go_latest"+
"?user=go_select&password=amigo"
);
//get all parents of go1
Map<String,Integer> acn2dist1=ancestors(go1);
//get all parents of go2
Map<String,Integer> acn2dist2=ancestors(go2);
connection.close();
//common terms
Set<String> acns=new HashSet<String>(acn2dist1.keySet());
acns.retainAll(acn2dist2.keySet());
if(acns.isEmpty()) return;
//find the minimal distance to a common term
Integer bestDist=null;
String bestTerm=null;
for(String acn:acns)
{
int d= acn2dist1.get(acn)+acn2dist2.get(acn);
if(bestDist==null || bestDist>d)
{
bestDist=d;
bestTerm=acn;
}
}
if(bestDist==null) return;
//print result
System.out.println(bestTerm+"\t"+(acn2dist1.get(bestTerm)+acn2dist2.get(bestTerm)));
}
public static void main(String args[])
throws Exception
{
if(args.length!=2) return;
new GoDistance().run(args[0],args[1]);
}
}
Compilation:
$ javac -Xlint GoDistance.java
Execution:
$ java -cp path/to/mysql-connector.jar:. GoDistance "GO:0001578" "GO:0030036"
GO:0007010 3