-
Notifications
You must be signed in to change notification settings - Fork 28
/
matrix.pm
460 lines (430 loc) · 25.4 KB
/
matrix.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package resources2::matrix;
use strict;
use warnings;
no warnings('once');
use POSIX qw(strftime);
use Conf;
use MGRAST::Metadata;
use MGRAST::Analysis;
use Babel::lib::Babel;
use Data::Dumper;
use parent qw(resources2::resource);
# Override parent constructor
sub new {
my ($class, @args) = @_;
# Call the constructor of the parent class
my $self = $class->SUPER::new(@args);
# Add name / attributes
$self->{name} = "matrix";
$self->{org2tax} = {};
$self->{cutoffs} = { evalue => '5', identity => '60', length => '15' };
$self->{hierarchy} = { organism => [ ['strain', 'bottom organism taxanomic level'],
['species', 'organism type level'],
['genus', 'organism taxanomic level'],
['family', 'organism taxanomic level'],
['order', 'organism taxanomic level'],
['class', 'organism taxanomic level'],
['phylum', 'organism taxanomic level'],
['domain', 'top organism taxanomic level'] ],
ontology => [ ['function', 'bottom function ontology level'],
['level3', 'function ontology level' ],
['level2', 'function ontology level' ],
['level1', 'top function ontology level'] ]
};
$self->{sources} = { organism => [ ["M5NR", "comprehensive protein database"],
["RefSeq", "protein database"],
["SwissProt", "protein database"],
["GenBank", "protein database"],
["IMG", "protein database"],
["SEED", "protein database"],
["TrEMBL", "protein database"],
["PATRIC", "protein database"],
["KEGG", "protein database"],
["M5RNA", "comprehensive RNA database"],
["RDP", "RNA database"],
["Greengenes", "RNA database"],
["LSU", "RNA database"],
["SSU", "RNA database"] ],
ontology => [ ["Subsystems", "ontology database, type function only"],
["NOG", "ontology database, type function only"],
["COG", "ontology database, type function only"],
["KO", "ontology database, type function only"] ]
};
$self->{attributes} = { "id" => [ 'string', 'unique object identifier' ],
"format" => [ 'string', 'format specification name' ],
"format_url" => [ 'string', 'url to the format specification' ],
"type" => [ 'string', 'type of the data in the return table (taxon, function or gene)' ],
"generated_by" => [ 'string', 'identifier of the data generator' ],
"date" => [ 'date', 'time the output data was generated' ],
"matrix_type" => [ 'string', 'type of the data encoding matrix (dense or sparse)' ],
"matrix_element_type" => [ 'string', 'data type of the elements in the return matrix' ],
"matrix_element_value" => [ 'string', 'result_type of the elements in the return matrix' ],
"shape" => [ 'list', ['integer', 'list of the dimension sizes of the return matrix'] ],
"rows" => [ 'list', ['object', [{'id' => ['string', 'unique annotation text'],
'metadata' => ['hash', 'key value pairs describing metadata']}, "rows object"]] ],
"columns" => [ 'list', ['object', [{'id' => ['string', 'unique metagenome identifier'],
'metadata' => ['hash', 'key value pairs describing metadata']}, "columns object"]] ],
"data" => [ 'list', ['list', ['float', 'the matrix values']] ]
};
return $self;
}
# resource is called without any parameters
# this method must return a description of the resource
sub info {
my ($self) = @_;
my $content = { 'name' => $self->name,
'url' => $self->cgi->url."/".$self->name,
'description' => "A profile in biom format that contains abundance counts",
'type' => 'object',
'documentation' => $Conf::cgi_url.'/Html/api.html#'.$self->name,
'requests' => [ { 'name' => "info",
'request' => $self->cgi->url."/".$self->name,
'description' => "Returns description of parameters and attributes.",
'method' => "GET" ,
'type' => "synchronous" ,
'attributes' => "self",
'parameters' => { 'options' => {},
'required' => {},
'body' => {} }
},
{ 'name' => "organism",
'request' => $self->cgi->url."/".$self->name."/organism",
'description' => "Returns a single data object.",
'method' => "GET" ,
'type' => "synchronous" ,
'attributes' => $self->attributes,
'parameters' => { 'options' => { 'evalue' => ['int', 'exponent value for maximum e-value cutoff: default is '.$self->{cutoffs}{evalue}],
'identity' => ['int', 'percent value for minimum % identity cutoff: default is '.$self->{cutoffs}{identity}],
'length' => ['int', 'value for minimum alignment length cutoff: default is '.$self->{cutoffs}{length}],
'result_type' => [ 'cv', [['abundance', 'number of reads with hits in annotation'],
['evalue', 'average e-value exponent of hits in annotation'],
['identity', 'average percent identity of hits in annotation'],
['length', 'average alignment length of hits in annotation']] ],
'source' => [ 'cv', $self->{sources}{organism} ],
'group_level' => [ 'cv', $self->{hierarchy}{organism} ],
'filter' => [ 'string', 'filter the return results to only include abundances based on genes with this function' ],
'filter_source' => [ 'cv', $self->{sources}{ontology} ],
'id' => [ 'string', 'one or more metagenome or project unique identifier' ] },
'required' => {},
'body' => {} }
},
{ 'name' => "function",
'request' => $self->cgi->url."/".$self->name."/function",
'description' => "Returns a single data object.",
'method' => "GET" ,
'type' => "synchronous" ,
'attributes' => $self->attributes,
'parameters' => { 'options' => { 'evalue' => ['int', 'exponent value for maximum e-value cutoff: default is '.$self->{cutoffs}{evalue}],
'identity' => ['int', 'percent value for minimum % identity cutoff: default is '.$self->{cutoffs}{identity}],
'length' => ['int', 'value for minimum alignment length cutoff: default is '.$self->{cutoffs}{length}],
'result_type' => [ 'cv', [['abundance', 'number of reads with hits in annotation'],
['evalue', 'average e-value exponent of hits in annotation'],
['identity', 'average percent identity of hits in annotation'],
['length', 'average alignment length of hits in annotation']] ],
'source' => [ 'cv', $self->{sources}{ontology} ],
'group_level' => [ 'cv', $self->{hierarchy}{ontology} ],
'filter' => [ 'string', 'filter the return results to only include abundances based on genes with this organism' ],
'filter_source' => [ 'cv', $self->{sources}{organism} ],
'id' => [ 'string', 'one or more metagenome or project unique identifier' ] },
'required' => {},
'body' => {} }
},
{ 'name' => "feature",
'request' => $self->cgi->url."/".$self->name."/feature",
'description' => "Returns a single data object.",
'method' => "GET" ,
'type' => "synchronous" ,
'attributes' => $self->attributes,
'parameters' => { 'options' => { 'result_type' => [ 'cv', [['abundance', 'number of reads with hits in annotation'],
['evalue', 'average e-value exponent of hits in annotation'],
['identity', 'average percent identity of hits in annotation'],
['length', 'average alignment length of hits in annotation']] ],
'source' => [ 'cv', [["RefSeq", "protein database"],
["SwissProt", "protein database"],
["GenBank", "protein database"],
["IMG", "protein database"],
["SEED", "protein database"],
["TrEMBL", "protein database"],
["PATRIC", "protein database"],
["KEGG", "protein database"],
["RDP", "RNA database"],
["Greengenes", "RNA database"],
["LSU", "RNA database"],
["SSU", "RNA database"]] ],
'id' => [ "string", "one or more metagenome or project unique identifier" ] },
'required' => {},
'body' => {} } }
] };
$self->return_data($content);
}
# Override parent request function
sub request {
my ($self) = @_;
# determine sub-module to use
if (scalar(@{$self->rest}) == 0) {
$self->info();
} elsif (($self->rest->[0] eq 'organism') || ($self->rest->[0] eq 'function') || ($self->rest->[0] eq 'feature')) {
$self->instance($self->rest->[0]);
} else {
$self->info();
}
}
# the resource is called with a parameter
sub instance {
my ($self, $type) = @_;
# get id set
unless ($self->cgi->param('id')) {
$self->return_data( {"ERROR" => "no ids submitted, aleast one 'id' is required"}, 400 );
}
my @ids = $self->cgi->param('id');
my $mgids = {};
my $seen = {};
# get database
my $master = $self->connect_to_datasource();
# get user viewable
my $m_star = ($self->user && $self->user->has_right(undef, 'view', 'metagenome', '*')) ? 1 : 0;
my $p_star = ($self->user && $self->user->has_right(undef, 'view', 'project', '*')) ? 1 : 0;
my $m_private = $master->Job->get_private_jobs($self->user, 1);
my $m_public = $master->Job->get_public_jobs(1);
my $p_private = $self->user ? $self->user->has_right_to(undef, 'view', 'project') : [];
my $p_public = $master->Project->get_public_projects(1);
my %m_rights = map {$_, 1} (@$m_private, @$m_public);
my %p_rights = map {$_, 1} (@$p_private, @$p_public);
# get unique list of mgids based on user rights and inputed ids
foreach my $id (@ids) {
next if (exists $seen->{$id});
if ($id =~ /^mgm(\d+\.\d+)$/) {
if ($m_star || exists($m_rights{$1})) {
$mgids->{$1} = 1;
} else {
$self->return_data( {"ERROR" => "insufficient permissions in matrix call for id: ".$id}, 401 );
}
} elsif ($id =~ /^mgp(\d+)$/) {
if ($p_star || exists($p_rights{$1})) {
my $proj = $master->Project->init( {id => $1} );
foreach my $mgid (@{ $proj->metagenomes(1) }) {
next unless ($m_star || exists($m_rights{$mgid}));
$mgids->{$mgid} = 1;
}
} else {
$self->return_data( {"ERROR" => "insufficient permissions in matrix call for id: ".$id}, 401 );
}
} else {
$self->return_data( {"ERROR" => "unknown id in matrix call: ".$id}, 401 );
}
$seen->{$id} = 1;
}
if (scalar(keys %$mgids) == 0) {
$self->return_data( {"ERROR" => "no valid ids submitted and/or found: ".join(", ", @ids)}, 401 );
}
# return cached if exists
$self->return_cached();
# prepare data
my $data = $self->prepare_data([keys %$mgids], $type);
$self->return_data($data, undef, 1); # cache this!
}
# reformat the data into the requested output format
sub prepare_data {
my ($self, $data, $type) = @_;
# get optional params
my $cgi = $self->cgi;
my $source = $cgi->param('source') ? $cgi->param('source') : (($type eq 'organism') ? 'M5NR' : (($type eq 'function') ? 'Subsystems': 'RefSeq'));
my $rtype = $cgi->param('result_type') ? $cgi->param('result_type') : 'abundance';
my $glvl = $cgi->param('group_level') ? $cgi->param('group_level') : (($type eq 'organism') ? 'strain' : 'function');
my $eval = defined($cgi->param('evalue')) ? $cgi->param('evalue') : $self->{cutoffs}{evalue};
my $ident = defined($cgi->param('identity')) ? $cgi->param('identity') : $self->{cutoffs}{identity};
my $alen = defined($cgi->param('length')) ? $cgi->param('length') : $self->{cutoffs}{length};
my $fsrc = $cgi->param('filter_source') ? $cgi->param('filter_source') : (($type eq 'organism') ? 'Subsystems' : 'M5NR');
my @filter = $cgi->param('filter') ? $cgi->param('filter') : ();
my $all_srcs = {};
my $leaf_node = 0;
my $matrix_id = join("_", map {'mgm'.$_} sort @$data).'_'.join("_", ($type, $glvl, $source, $rtype, $eval, $ident, $alen));
if (@filter > 0) {
$matrix_id .= join("_", sort map { $_ =~ s/\s+/_/g } @filter)."_".$fsrc;
}
# initialize analysis obj with mgids
my $master = $self->connect_to_datasource();
my $mgdb = MGRAST::Analysis->new( $master->db_handle );
unless (ref($mgdb)) {
$self->return_data({"ERROR" => "could not connect to analysis database"}, 500);
}
$mgdb->set_jobs($data);
# validate cutoffs
if (int($eval) < 1) {
$self->return_data({"ERROR" => "invalid evalue for matrix call, must be integer greater than 1"}, 500);
}
if ((int($ident) < 0) || (int($ident) > 100)) {
$self->return_data({"ERROR" => "invalid identity for matrix call, must be integer between 0 and 100"}, 500);
}
if (int($alen) < 1) {
$self->return_data({"ERROR" => "invalid length for matrix call, must be integer greater than 1"}, 500);
}
# controlled vocabulary set
my $result_idx = { abundance => {function => 3, organism => 10, feature => 2},
evalue => {function => 5, organism => 12, feature => 3},
length => {function => 7, organism => 14, feature => 5},
identity => {function => 9, organism => 16, feature => 7}
};
my $result_map = {abundance => 'abundance', evalue => 'exp_avg', length => 'len_avg', identity => 'ident_avg'};
my @func_hier = map { $_->[0] } @{$self->{hierarchy}{ontology}};
my @org_hier = map { $_->[0] } @{$self->{hierarchy}{organism}};
my $type_set = ["function", "organism", "feature"];
# validate controlled vocabulary params
unless (exists $result_map->{$rtype}) {
$self->return_data({"ERROR" => "invalid result_type for matrix call: ".$rtype." - valid types are [".join(", ", keys %$result_map)."]"}, 500);
}
if ($type eq 'organism') {
map { $all_srcs->{$_->[0]} = 1 } @{$mgdb->sources_for_type('protein')};
map { $all_srcs->{$_->[0]} = 1 } @{$mgdb->sources_for_type('rna')};
if ( grep(/^$glvl$/, @org_hier) ) {
$glvl = 'tax_'.$glvl;
if ($glvl eq 'tax_strain') {
$glvl = 'name';
$leaf_node = 1;
}
} else {
$self->return_data({"ERROR" => "invalid group_level for matrix call of type ".$type.": ".$glvl." - valid types are [".join(", ", @org_hier)."]"}, 500);
}
} elsif ($type eq 'function') {
map { $all_srcs->{$_->[0]} = 1 } grep { $_->[0] !~ /^GO/ } @{$mgdb->sources_for_type('ontology')};
if ( grep(/^$glvl$/, @func_hier) ) {
if ($glvl eq 'function') {
$glvl = ($source =~ /^[NC]OG$/) ? 'level3' : 'level4';
}
if ( ($glvl eq 'level4') || (($source =~ /^[NC]OG$/) && ($glvl eq 'level3')) ) {
$leaf_node = 1;
}
} else {
$self->return_data({"ERROR" => "invalid group_level for matrix call of type ".$type.": ".$glvl." - valid types are [".join(", ", @func_hier)."]"}, 500);
}
} elsif ($type eq 'feature') {
map { $all_srcs->{$_->[0]} = 1 } @{$mgdb->sources_for_type('protein')};
map { $all_srcs->{$_->[0]} = 1 } @{$mgdb->sources_for_type('rna')};
delete $all_srcs->{M5NR};
delete $all_srcs->{M5RNA};
}
unless (exists $all_srcs->{$source}) {
$self->return_data({"ERROR" => "invalid source for matrix call of type ".$type.": ".$source." - valid types are [".join(", ", keys %$all_srcs)."]"}, 500);
}
# get data
my $md52id = {};
my $ttype = '';
my $mtype = '';
my $matrix = []; # [ row <annotation>, col <mgid>, value ]
my $col_idx = $result_idx->{$rtype}{$type};
my $umd5s = [];
if ($type eq 'organism') {
$ttype = 'Taxon';
$mtype = 'taxonomy';
if (@filter > 0) {
$umd5s = $mgdb->get_md5s_for_ontology(\@filter, $fsrc);
}
unless ((@filter > 0) && (@$umd5s == 0)) {
if ($leaf_node) {
# my ($self, $md5s, $sources, $eval, $ident, $alen, $with_taxid) = @_;
my (undef, $info) = $mgdb->get_organisms_for_md5s($umd5s, [$source], int($eval), int($ident), int($alen));
# mgid, source, tax_domain, tax_phylum, tax_class, tax_order, tax_family, tax_genus, tax_species, name, abundance, sub_abundance, exp_avg, exp_stdv, ident_avg, ident_stdv, len_avg, len_stdv, md5s
@$matrix = map {[ $_->[9], $_->[0], $self->toNum($_->[$col_idx], $rtype) ]} @$info;
map { $self->{org2tax}->{$_->[9]} = [ @$_[2..9] ] } @$info;
} else {
# my ($self, $level, $names, $srcs, $value, $md5s, $eval, $ident, $alen) = @_;
@$matrix = map {[ $_->[1], $_->[0], $self->toNum($_->[2], $rtype) ]} @{$mgdb->get_abundance_for_tax_level($glvl, undef, [$source], $result_map->{$rtype}, $umd5s, int($eval), int($ident), int($alen))};
# mgid, hier_annotation, value
}
}
} elsif ($type eq 'function') {
$ttype = 'Function';
$mtype = 'ontology';
if (@filter > 0) {
$umd5s = $mgdb->get_md5s_for_organism(\@filter, $fsrc);
}
unless ((@filter > 0) && (@$umd5s == 0)) {
if ($leaf_node) {
# my ($self, $md5s, $source, $eval, $ident, $alen) = @_;
my (undef, $info) = $mgdb->get_ontology_for_md5s($umd5s, $source, int($eval), int($ident), int($alen));
# mgid, id, annotation, abundance, sub_abundance, exp_avg, exp_stdv, ident_avg, ident_stdv, len_avg, len_stdv, md5s
@$matrix = map {[ $_->[1], $_->[0], $self->toNum($_->[$col_idx], $rtype) ]} @$info;
} else {
# my ($self, $level, $names, $src, $value, $md5s, $eval, $ident, $alen) = @_;
@$matrix = map {[ $_->[1], $_->[0], $self->toNum($_->[2], $rtype) ]} @{$mgdb->get_abundance_for_ontol_level($glvl, undef, $source, $result_map->{$rtype}, $umd5s, int($eval), int($ident), int($alen))};
# mgid, hier_annotation, value
}
}
} elsif ($type eq 'feature') {
$ttype = 'Gene';
$mtype = $source.' ID';
# my ($self, $md5s, $eval, $ident, $alen, $ignore_sk, $rep_org_src) = @_;
my $info = $mgdb->get_md5_data(undef, int($eval), int($ident), int($alen), 1);
# mgid, md5, abundance, exp_avg, exp_stdv, ident_avg, ident_stdv, len_avg, len_stdv
my %md5s = map { $_->[1], 1 } @$info;
my $mmap = $mgdb->decode_annotation('md5', [keys %md5s]);
map { push @{$md52id->{ $mmap->{$_->[1]} }}, $_->[0] } @{ $mgdb->annotation_for_md5s([keys %md5s], [$source]) };
@$matrix = map {[ $_->[1], $_->[0], $self->toNum($_->[$col_idx], $rtype) ]} grep {exists $md52id->{$_->[1]}} @$info;
}
@$matrix = sort { $a->[0] cmp $b->[0] || $a->[1] cmp $b->[1] } @$matrix;
my $row_ids = $self->sorted_hash($matrix, 0);
my $col_ids = $self->sorted_hash($matrix, 1);
# produce output
my $brows = [];
my $bcols = [];
my $r_map = ($type eq 'feature') ? $md52id : $self->get_hierarchy($mgdb, $type, $glvl, $source, $leaf_node);
foreach my $rid (sort {$row_ids->{$a} <=> $row_ids->{$b}} keys %$row_ids) {
my $rmd = exists($r_map->{$rid}) ? { $mtype => $r_map->{$rid} } : undef;
push @$brows, { id => $rid, metadata => $rmd };
}
my $mddb = MGRAST::Metadata->new();
my $meta = $mddb->get_jobs_metadata_fast($data, 1);
my $name = $mgdb->_name_map();
foreach my $cid (sort {$col_ids->{$a} <=> $col_ids->{$b}} keys %$col_ids) {
my $cmd = exists($meta->{$cid}) ? $meta->{$cid} : undef;
my $cnm = exists($name->{$cid}) ? $name->{$cid} : undef;
push @$bcols, { id => 'mgm'.$cid, name => $cnm, metadata => $cmd };
}
my $obj = { "id" => $matrix_id,
"format" => "Biological Observation Matrix 1.0",
"format_url" => "http://biom-format.org",
"type" => $ttype." table",
"generated_by" => "MG-RAST revision ".$Conf::server_version,
"date" => strftime("%Y-%m-%dT%H:%M:%S", localtime),
"matrix_type" => "sparse",
"matrix_element_type" => ($rtype eq 'abundance') ? "int" : "float",
"matrix_element_value" => $rtype,
"shape" => [ scalar(keys %$row_ids), scalar(keys %$col_ids) ],
"rows" => $brows,
"columns" => $bcols,
"data" => $self->index_sparse_matrix($matrix, $row_ids, $col_ids)
};
return $obj;
}
sub get_hierarchy {
my ($self, $mgdb, $type, $level, $src, $leaf_node) = @_;
if ($type eq 'organism') {
return $leaf_node ? $self->{org2tax} : $mgdb->get_hierarchy('organism', undef, undef, undef, $level);
} elsif ($type eq 'function') {
return $leaf_node ? $mgdb->get_hierarchy('ontology', $src) : $mgdb->get_hierarchy('ontology', $src, undef, undef, $level);
} else {
return {};
}
}
sub index_sparse_matrix {
my ($self, $matrix, $rows, $cols) = @_;
my $sparse = [];
foreach my $pos (@$matrix) {
my ($r, $c, $v) = @$pos;
push @$sparse, [ $rows->{$r}, $cols->{$c}, $v ];
}
return $sparse;
}
sub sorted_hash {
my ($self, $array, $idx) = @_;
my $pos = 0;
my $out = {};
my @sub = sort map { $_->[$idx] } @$array;
foreach my $x (@sub) {
next if (exists $out->{$x});
$out->{$x} = $pos;
$pos += 1;
}
return $out;
}
1;