Debian Codegraph @

scripts/map2slim

raw
1 #!/usr/local/bin/perl -w
2
3 # POD docs at end of file
4
5 use strict;
6 use FileHandle;
7 use GO::Parser;
8
9 if (!@ARGV) {
10 system("perldoc $0");
11 exit;
12 }
13 if ("@ARGV" eq "-h") {
14 system("perldoc $0");
15 exit;
16 }
17
18 use Getopt::Long;
19 my $opt = {};
20 GetOptions($opt,
21 "help",
22 "dbname|d=s",
23 "host|h=s",
24 "out|o=s",
25 "err|e=s",
26 "force",
27 "ontdir=s",
28 "outmap=s",
29 "shownames",
30 "cache=s",
31 "inmap=s",
32 "gff",
33 "aspect|a=s",
34 "count|c",
35 "tab|t",
36 "bucket|b=s",
37 "evcode|ev=s@",
38 "verbose|v");
39
40 if ($opt->{help}) {
41 system("perldoc $0");
42 exit;
43 }
44 my $verbose = $opt->{verbose};
45
46 # cached results
47 my %memo_mapslim = ();
48
49 my $slimfile = shift @ARGV;
50 my $assocfile;
51 $assocfile = pop @ARGV unless $opt->{outmap};
52 my @ontfiles = @ARGV;
53
54 if ($opt->{ontdir}) {
55 @ontfiles = glob($opt->{ontdir}."/*{obo}");
56 @ontfiles = glob($opt->{ontdir}."/*{ontology}") unless @ontfiles;
57 }
58
59 # parse GO-slim and get the slim graph
60 my $parser = GO::Parser->new({handler=>'obj'});
61 printf STDERR "Parsing slimfile: $slimfile\n" if $verbose;
62 $parser->parse($slimfile);
63 my $gslim = $parser->handler->graph;
64
65 # optionally add "slop" terms; eg "OTHER nucleotide binding"
66 my $bucketf = $opt->{bucket};
67 if ($bucketf) {
68 printf STDERR "Adding bucket terms to: $bucketf\n" if $verbose;
69 $gslim->add_buckets;
70 if (-f $bucketf && !$opt->{force}) {
71 printf STDERR "Overwrite existing $bucketf file?\n(use -force option to skip this prompt)\n";
72 my $yesno = <STDIN>;
73 unless ($yesno =~ /^y/i) {
74 printf STDERR "Will not overwrite $bucketf. Quitting!\n";
75 exit 1;
76 }
77 }
78 my $fh = FileHandle->new(">$bucketf") ||
79 die("can't write to $bucketf");
80 $gslim->to_text_output(-fh=>$fh);
81 $fh->close;
82 }
83
84 # make a hash of term objects keyed by slim term accession
85 my $slimterms = $gslim->get_all_terms;
86 my %slimh = map {$_->acc => $_} @$slimterms;
87
88 # parse full ontology
89
90 # use cache if required (secret option)
91 my $cache = $opt->{cache};
92 require "Storable.pm" if $cache;
93 my $ont;
94 if ($cache && -f $cache) {
95 print STDERR "Using cache: $cache\n" if $verbose;
96 #$ont = YAML::LoadFile($cache);
97 $ont = Storable::retrieve($cache);
98 }
99 else {
100 if ($opt->{dbname}) {
101 # secret db mode
102 require "GO/AppHandle.pm";
103 my $apph = GO::AppHandle->connect(-dbname=>$opt->{dbname},
104 -dbhost=>$opt->{host},
105 );
106 $ont = $apph->get_graph(-template=>{terms=>{acc=>1}});
107 $apph->disconnect;
108 }
109 else {
110 my $parser2 = GO::Parser->new({handler=>'obj'});
111 foreach my $ontfile (@ontfiles) {
112 printf STDERR "Parsing ontology file: $ontfile\n" if $verbose;
113 $parser2->litemode(1);
114 $parser2->parse($ontfile);
115 }
116 $ont = $parser2->handler->graph;
117 }
118 if ($cache) {
119 print STDERR "Writing to cache: $cache\n" if $verbose;
120 #print YAML::DumpFile($cache, $ont);
121 store($ont, $cache);
122 }
123 }
124
125 # write output to stdout or a file
126 my $ofh;
127 if ($opt->{out}) {
128 $ofh = FileHandle->new(">".$opt->{out}) || die($opt->{out});
129 }
130 else {
131 $ofh = \*STDOUT;
132 }
133
134 # initialize counts to 0
135 my %countleaf = map { ($_ => 0) } keys %slimh;
136 my %countall = %countleaf;
137
138 # write out slim mappings and exit if in outmap mode
139 if ($opt->{outmap}) {
140 printf STDERR "Writing slim mappings\n" if $verbose;
141 my $outmap = FileHandle->new(">$opt->{outmap}") ||
142 die("cannot open $opt->{outmap} for writing");
143 # write slim mapping for all GO terms
144 my $terms = $ont->get_all_terms;
145 foreach my $t (sort {$a->acc cmp $b->acc} @$terms) {
146 my $acc = $t->acc;
147 my ($leaf_pnodes, $all_pnodes) = mapslim($acc);
148 if ($opt->{shownames}) {
149 printf $outmap "%s => %s // %s\n",
150 fmt_acc_names($acc),
151 fmt_acc_names(@$leaf_pnodes),
152 fmt_acc_names(@$all_pnodes),
153 }
154 else {
155 print $outmap "$acc => @$leaf_pnodes // @$all_pnodes\n";
156 }
157 }
158 $outmap->close;
159 exit 0;
160 }
161
162 # use pre-made mappings
163 if ($opt->{inmap}) {
164 printf STDERR "Using predefined mappings\n" if $verbose;
165 my $inmap = FileHandle->new(">$opt->{inmap}") ||
166 die("cannot open $opt->{inmap}");
167 while (<$inmap>) {
168 chomp;
169 if (/(\S+)\s*=\>\s*(.*)\s+\/\.\s+(.*)/) {
170 my $acc = $1;
171 $memo_mapslim{$acc} =
172 [[split(' ', $2)], [split(' ', $3)]];
173 }
174 else {
175 warn("illegal slimmap line: $_");
176 }
177 }
178 $inmap->close;
179 exit 0;
180 }
181
182 # hash of hashes - maps slim accessions to gene products
183 # key of outer hash is slim accession
184 # key of inner hash is gene product accession
185 # value is boolean
186 my %leafh = ();
187 my %allh = ();
188
189 my %counted = ();
190 my $fh;
191 if ($assocfile =~ /\.(Z|gz)$/) {
192 printf STDERR "Uncompressing and mapping $assocfile to slim\n" if $verbose;
193 $fh = FileHandle->new("gzip -dc $assocfile|") ||
194 die("cannot open assocfile: $assocfile");
195 }
196 else {
197 printf STDERR "Mapping $assocfile to slim\n" if $verbose;
198 $fh = FileHandle->new($assocfile) ||
199 die("cannot open assocfile: $assocfile");
200 }
201
202 my $gff = $opt->{gff};
203 while(<$fh>) {
204 next if /^\!/;
205 chomp;
206 next unless $_;
207 my @cols = split('\t', $_);
208 my $is_not = $cols[3];
209 my $acc = $cols[4];
210 if ($gff) {
211 $is_not = 0;
212 my $type = $cols[2];
213 if ($type =~ /^SO:/) {
214 $acc = $type;
215 }
216 else {
217 my $term = $ont->get_term_by_name($type);
218 if (!$term) {
219 warn("ignoring type: $type");
220 next;
221 }
222 $acc = $term->acc;
223 }
224 }
225 if (!$acc) {
226 printf STDERR "WARNING! NO ACCESSION: $_\n" if $verbose;
227 next;
228 }
229 my $prod = $cols[1];
230 if ($gff) {
231 $prod = $cols[8];
232 }
233
234 next if $is_not && $is_not =~ /^not$/i; # skip NOT assocs
235 if ($opt->{aspect}) {
236 next unless $cols[8] eq $opt->{aspect};
237 }
238 if ($opt->{count}) {
239 # save time - if we've encoutered this pair before
240 # then skip it
241 next if $counted{$acc.$prod};
242 $counted{$acc.$prod} = 1;
243 }
244
245 # map the annotated GO term up to the slim term(s)
246 my ($leaf_pnodes, $all_pnodes) = mapslim($acc);
247
248 # mark the gene product as belonging to that slim term
249 $leafh{$_}->{$prod} = 1 foreach @$leaf_pnodes;
250 $allh{$_}->{$prod} = 1 foreach @$all_pnodes;
251
252 unless ($opt->{count}) {
253 foreach my $replacement_acc (@$leaf_pnodes) {
254 if ($gff) {
255 $cols[2] = $replacement_acc;
256 }
257 else {
258 $cols[4] = $replacement_acc;
259 }
260 print $ofh join("\t", @cols), "\n";
261 }
262 }
263 }
264 close($fh) || die("problem reading $assocfile");
265
266
267 if ($opt->{count}) {
268 printf STDERR "Getting gene product counts\n" if $verbose;
269
270 # iterate through the slim graph, depth-first traversal,
271 # printing out slim term accession & name, and the total
272 # distinct gene products attached to that term or its children
273 $gslim->iterate(
274 sub {
275 my $ni = shift;
276 my $t = $ni->term;
277 return if $t->is_relationship_type;
278
279 my $acc = $t->acc;
280 my $t2; # equivalent term in GO-full
281 if ($acc) {
282 $t2 = $ont->get_term($acc);
283 } else {
284 # no equivalent term - the slim id has been
285 # retired and not tracked; this should
286 # only happen with old slims
287 $acc = "NO_ACC";
288 }
289 if ($opt->{tab}) {
290 my $depth = $ni->depth +1;
291 printf $ofh ' ' x $depth;
292 }
293 my $count_leaf = scalar(keys %{$leafh{$acc} || {}}) || 0;
294 my $count_all = scalar(keys %{$allh{$acc} || {}}) || 0;
295
296 printf $ofh ("%s %s (%s)\t%d\t%d\t%s\t%s\n",
297 $acc,
298 $t->name,
299 $t2 && $t2->name ? $t2->name : '?',
300 $count_leaf || 0,
301 $count_all || 0,
302 $t2 && $t2->is_obsolete ? 'OBSOLETE' : '',
303 $t->type || '',
304 );
305 return;
306 },
307 {no_duplicates=>1}
308 );
309 }
310 $ofh->close;
311 printf STDERR "Done!\n" if $verbose;
312 exit 0;
313
314 # function: mapslim($acc)
315 #
316 # argument: accession [in full GO]
317 # returns: slim-direct-acc-list, slim-all-acc-list
318 #
319 # slim-direct-acc-list is the slim accs that the input acc DIRECTLY maps to
320 # - this corresponds to the most pertinent slim term
321 #
322 # slim-all-acc-list is the slim accs that the input acc maps to
323 # DIRECT & INDIRECT
324 # - this corresponds to ALL the slim terms that are ancestors of input term
325 #
326 # algorithm for finding most pertinent slim term:
327 #
328 # IF a GO acc has two ancestors in the slim,
329 # AND the parents are NOT ancestors of one another
330 # THEN the acc maps to BOTH parents
331 #
332 # IF an acc has two ancestors in the slim,
333 # AND the parents ARE ancestors of one another,
334 # THEN the MORE SPECIFIC parent acc is returned
335 #
336 sub mapslim {
337 my $acc = shift;
338
339 # save time - never recompute on the same accession
340 my $memo = $memo_mapslim{$acc};
341 return (@$memo) if $memo; # return same result
342
343 # trace the paths to root of the input acc in the full GO
344 # (there may be multiple paths to the root)
345 my $paths = $ont->paths_to_top($acc);
346
347 my $term = $ont->get_term($acc);
348 if (!$term) {
349 # no such accession in GO
350 return ([],[]);
351 }
352
353 # keep hash, keyed by slim accession, boolean value -
354 # will have true if the slim term is an ancestor of $acc
355 my %ancestorh = (); # ALL ancestors of $acc in slim
356 my %pancestorh = (); # ancestors of $acc in slim for which there
357 # is a path through another ancestor
358
359 foreach my $path (@$paths) {
360 my $terms = $path->term_list;
361 unshift(@$terms, $term); # make path inclusive of base term
362
363 # if there are "slop" terms (eg OTHER nucleotide binding)
364 # AND there is an IMPLICIT path through this slop term,
365 # then add this to the explicit path
366 if ($opt->{bucket}) {
367 my $got_leaf = 0;
368 @$terms =
369 map {
370 my $slimt = $slimh{$_};
371 my @R = ($_);
372 if ($slimt && !$got_leaf) {
373 my $crs = $gslim->get_child_relationships($_);
374 my @brels = grep {$_->type eq "bucket"} @$crs;
375 if (@brels) {
376 my $bterm = $gslim->get_term($brels[0]->acc2);
377 @R = ($bterm, $_);
378 }
379 }
380 if ($slimt) {
381 $got_leaf = 1;
382 }
383 @R;
384 } @$terms;
385 }
386
387 my $got_leaf = 0;
388 # follow path from $acc up to root, checking to
389 # see if the intermediate term is in the slim
390 foreach my $term (@$terms) {
391 my $pacc = $term->acc;
392
393 if ($slimh{$pacc}) {
394 # intermediate term is in the slim
395 $ancestorh{$pacc} = 1;
396 if ($got_leaf) {
397 $pancestorh{$pacc} = 1;
398 }
399 $got_leaf = 1;
400 }
401 }
402 }
403 # find unique ancestors, ie ancestors that are not intermediates to
404 # another anestor
405 my @uancestors = grep {!$pancestorh{$_}} keys %ancestorh;
406 $memo = [[@uancestors], [keys %ancestorh]];
407 #printf STDERR "SLIM($acc) = @{$memo->[0]} // @{$memo->[1]}\n";
408 $memo_mapslim{$acc} = $memo;
409 return @$memo;
410 }
411
412 sub fmt_acc_names {
413 my @accs = @_;
414 return join(' ',
415 map {
416 my $t = $ont->get_term($_);
417 if (!$t) {
418 $t = $gslim->get_term($_);
419 }
420 sprintf('%s "%s"',$_,$t ? $t->name : '?');
421 } @accs);
422 }
423
424 __END__
425
426 =head1 NAME
427
428 map2slim - maps gene associations to a 'slim' ontology
429
430 =head1 SYNOPSIS
431
432 cd go
433 map2slim GO_slims/goslim_generic.obo ontology/gene_ontology.obo gene-associations/gene_association.fb
434
435 =head1 DESCRIPTION
436
437 Given a GO slim file, and a current ontology (in one or more files),
438 this script will map a gene association file (containing annotations
439 to the full GO) to the terms in the GO slim.
440
441 The script can be used to either create a new gene association file,
442 containing the most pertinent GO slim accessions, or in count-mode, in
443 which case it will give distinct gene product counts for each slim
444 term
445
446 The association file format is described here:
447
448 L<http://www.geneontology.org/GO.annotation.shtml#file>
449
450
451 =head1 ARGUMENTS
452
453 =over
454
455 =item -b B<bucket slim file>
456
457 This argument adds B<bucket terms> to the slim ontology; see the
458 documentation below for an explanation. The new slim ontology file,
459 including bucket terms will be written to B<bucket slim file>
460
461 =item -outmap B<slim mapping file>
462
463 This will generate a mapping file for every term in the full ontology
464 showing both the most pertinent slim term and all slim terms that are
465 ancestors. If you use this option, do NOT supply a gene-associations
466 file
467
468 =item shownames
469
470 (Only works with -outmap)
471
472 Show the names of the term in the slim mapping file
473
474 =item -c
475
476 This will force map2slim to give counts of the assoc file, rather than map it
477
478 =item -t
479
480 When used in conjunction with B<-c> will tab the output so that the
481 indentation reflects the tree hierarchy in the slim file
482
483 =item -o B<out file>
484
485 This will write the mapped assocs (or counts) to the specified file,
486 rather than to the screen
487
488 =back
489
490 =head1 DOWNLOAD
491
492 This script is part of the B<go-perl> package, available from CPAN
493
494 L<http://search.cpan.org/~cmungall/go-perl/>
495
496 This script will not work without installing go-perl
497
498 =head2 MAPPING ALGORITHM
499
500 GO is a DAG, not a tree. This means that there is often more than one
501 path from a GO term up to the root Gene_Ontology node; the path may
502 intersect multiple terms in the slim ontology - which means that one
503 annotation can map to multiple slim terms!
504
505 (B<note> you need to view this online to see the image below - if you
506 are not viewing this on the http://www.geneontology.org site, you can look at the following URL:
507 L<http://geneontology.cvs.sourceforge.net/*checkout*/geneontology/go-dev/go-perl/doc/map2slim.gif> )
508
509 =begin html
510
511 <img src="http://geneontology.cvs.sourceforge.net/*checkout*/geneontology/go-dev/go-perl/doc/map2slim.gif"/>
512
513 =end html
514
515 A hypothetical example blue circles show terms in the GO slim, and yellow circles show terms in the full ontology. The full ontology subsumes the slim, so the blue terms are also in the ontology.
516
517 GO ID MAPS TO SLIM ID ALL SLIM ANCESTORS
518 ===== =============== ==================
519 5 2+3 2,3,1
520 6 3 only 3,1
521 7 4 only 4,3,1
522 8 3 only 3,1
523 9 4 only 4,3,1
524 10 2+3 2,3,1
525
526
527 The 2nd column shows the most pertinent ID(s) in the slim the direct mapping. The 3rd column shows all ancestors in the slim.
528
529 Note in particular the mapping of ID 9 although this has two paths to the root through the slim via 3 and 4, 3 is discarded because it is subsumed by 4.
530
531 On the other hand, 10 maps to both 2 and 3 because these are both the first slim ID in the two valid paths to the root, and neither subsumes the other.
532
533 The algorithm used is:
534
535 to map any one term in the full ontology:
536 find all valid paths through to the root node in the full ontology
537
538 for each path, take the first slim term encountered in the path
539
540 discard any redundant slim terms in this set ie slim terms subsumed by other slim terms in the set
541
542 =head2 BUCKET TERMS
543
544 If you run the script with the -b option, bucket terms will be added. For any term P in the slim, if P has at least one child C, a bucket term P' will be created under P. This is a catch-all term for mapping any term in the full ontology that is a descendant of P, but NOT a descendant of any child of P in the slim ontology.
545
546 For example, the slim generic.0208 has the following terms and structure:
547
548 %DNA binding ; GO:0003677
549 %chromatin binding ; GO:0003682
550 %transcription factor activity ; GO:0003700, GO:0000130
551
552 After adding bucket terms, it will look like this:
553
554 %DNA binding ; GO:0003677
555 %chromatin binding ; GO:0003682
556 %transcription factor activity ; GO:0003700 ; synonym:GO:0000130
557 @bucket:Z-OTHER-DNA binding ; slim_temp_id:12
558
559 Terms from the full ontology that are other children of DNA binding, such as single-stranded DNA binding and its descendents will map to the bucket term.
560
561 The bucket term has a slim ID which is transient and is there only to facilitate the mapping. It should not be used externally.
562
563 The bucket term has the prefix Z-OTHER; the Z is a hack to make sure that the term is always listed last in the alphabetic ordering.
564
565 The algorithm is slightly modified if bucket terms are used. The bucket term has an implicit relationship to all OTHER siblings not in the slim.
566
567 =head3 Do I need bucket terms?
568
569 Nowadays most slim files are entirely or nearly 'complete', that is
570 there are no gaps. This means the the -b option will not produce
571 noticeable different results. For example, you may see a bucket term
572 OTHER-binding created, with nothing annotated to it: because all the
573 children of binding in the GO are represented in the slim file.
574
575 The bucket option is really only necessary for some of the older
576 archived slim files, which are static and were generated in a fairly
577 ad-hoc way; they tend to accumulate 'gaps' over time (eg GO will add a
578 new child of binding, but the static slim file won't be up to date, so
579 any gene products annotated to this new term will map to OTHER-binding
580 in the slim)
581
582 =head2 GRAPH MISMATCHES
583
584 Note that the slim ontology file(s) may be out of date with respect to
585 the current ontology.
586
587 Currently map2slim does not flag graph mismatches between the slim
588 graph and the graph in the full ontology file; it takes the full
589 ontology as being the real graph. However, the slim ontology will be
590 used to format the results if you select B<-t -c> as options.
591
592 =head2 OUTPUT
593
594 In normal mode, a standard format gene-association file will be
595 written. The GO ID column (5) will contain GO slim IDs. The mapping
596 corresponds to the 2nd column in the table above. Note that the output
597 file may contain more lines that the input file. This is because some
598 full GO IDs have more than one pertinent slim ID.
599
600 =head3 COUNT MODE
601
602 map2slim can be run with the -c option, which will gives the counts of
603 distinct gene products mapped to each slim term. The columns are as follows
604
605 =over
606
607 =item GO Term
608
609 The first column is the GO ID followed by the term name (the term name
610 is provided as it is found in both the full GO and slim ontologies -
611 these will usually be the same but occasionally the slim file will
612 lage behind changes in the GO file)
613
614 =item Count of gene products for which this is the most relevant slim term
615
616 the number of distinct gene products for which this is the most
617 pertinent/direct slim ID. By most direct we mean that either the
618 association is made directly to this term, OR the association is made
619 to a child of this slim term AND there is no child slim term which the
620 association maps to.
621
622 For most slims, this count will be equivalent to the number of
623 associations directly mapped to this slim term. However, some older
624 slim files are "spotty" in that they admit "gaps". For example, if the
625 slim has all children of "biological process" with the exception of
626 "behavior" then all annotations to "behavior" or its children will be
627 counted here
628
629 see example below
630
631 =item Count of gene products inferred to be associated with slim term
632
633 and the number of distinct gene products which are annotated
634 to any descendant of this slim ID (or annotated directly to the slim
635 ID).
636
637 =item obsoletion flag
638
639 =item GO ontology
640
641 =back
642
643 To take an example; if we use -t and -c like this:
644
645 map2slim -t -c GO_slims/goslim_generic.obo ontology/gene_ontology.obo gene-associations/gene_association.fb
646
647 Then part of the results may look like this:
648
649 GO:0008150 biological_process (biological_process) 34 10025 biological_process
650 GO:0007610 behavior (behavior) 632 632 biological_process
651 GO:0000004 biological process unknown (biological process unknown) 832 832 biological_process
652 GO:0007154 cell communication (cell communication) 333 1701 biological_process
653 GO:0008037 cell recognition (cell recognition) 19 19 biological_process
654 19 products were mapped to GO:0008037 or one of its children. (GO:0008037 is a leaf node in the slim, so the two counts are identical).
655
656 On the other hand, GO:0008150 only gets 34 products for which this is
657 the most relevant term. This is because most annotations would map to
658 some child of GO:0008150 in the slim, such as GO:0007610
659 (behavior). These 34 gene products are either annotated directly to
660 GO:0008150, or to some child of this term which is not in the
661 slim. This can point to 'gaps' in the slim. Note that running map2slim
662 with the -b option will 'plug' these gaps with artificial filler terms.
663
664
665 =head1 AUTHOR
666
667 Chris Mungall BDGP
668
669 =head1 SEE ALSO
670
671 http://www.godatabase.org/dev
672
673 L<GO::Parser>
674
675 L<GO::Model::Graph>
676
677 =cut
678