Debian Codegraph @

TFBS/DB/JASPAR7.pm

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 # TFBS module for TFBS::DB::JASPAR
2 #
3 # Copyright Boris Lenhard
4 #
5 # You may distribute this module under the same terms as perl itself
6 #
7 # Maintainers:
8 # Xiaobei Zhao - JASPAR6 (JASPAR 2014 experimental)
9 # David Arenillas - JASPAR7 (JASPAR 2016)
10 #
11 # This is an update of, and follows from TFBS::DB::JASPAR6 which itself was
12 # created / modified from JASPAR5 by Xiaobei Zhao. It was created
13 # by copying the existing TFBS::DB::JASPAR6 and modifying it to reflect the
14 # changes made to the 2016 update of the JASPAR database / webserver.
15 #
16 # As there seemed to be some discrepancy / confusion between the version
17 # numbers with the JASPAR DB/webserver releases and the perl module, from
18 # now on the latest (current) version of the perl module will simply be named
19 # JASPAR.pm (without version number attached). Previous versions will have a
20 # version number attached to them to indicate which DB/webserver they are
21 # related to.
22 #
23 # JASPAR 5 and 6 are associated with JASPAR 2014 (also known as JASPAR 5.0).
24 # It appears that the JASPAR6 perl module was an experimental update to
25 # JASPAR5 and did not reflect a version change in the JASPAR DB/webserver.
26 #
27 # Change summary since JASPAR[5/6].pm:
28 # - In the _store_matrix routine, the code was checking for a version number
29 # by checking for a 'version' tag and NOT even checking to see if the version
30 # number was already contained in the matrix ID!?!? Modified to first check
31 # for a version encoded in the matrix ID and then only if it isn't, check for
32 # a version tag.
33 # - Fixed the way the 'acc' tag is stored.
34 # - The DB schema was changed to allow multiple values for a given matrix in
35 # some instances where previously only a single value was allowed. E.g. for
36 # the MATRIX_ANNOTATION table, removed the unique key constrain on ID + TAG
37 # so that multiple VALs with the same TAG can be stored for a given matrix.
38 # As it was, multiple values were already stored as comma separated values
39 # in a single row which is bad DB design (not normalized). The Code was thus
40 # modified to reflect that these values may now be stored in multiple DB
41 # rows.
42 # - Related to this, previously it was assumed that TF class and family could
43 # each only be a single value. However, for heterodimers it is quite possible
44 # that the two TFs making up the dimer have a different class/family so now
45 # the code assumes multiple could exist in the DB for these tags. As a result
46 # the class/family may now be stored in a TFBS::Matrix object as either a
47 # scalar string (for a single value) or as a listref (for multiple values).
48 # This is consistent with the way other tag/values are stored although
49 # it can certainly be argued that it is not good programming style to have
50 # different return types for the same method! This behaviour should be
51 # reconsidered in future versions of the TFBS modules.
52 # - Similarly to values stored in MATRIX_ANNOTATION, the MATRIX_SPECIES table
53 # has been modified to allow storage or multiple species for a matrix as
54 # separate rows rather than as comma separated strings and related code
55 # modified accordingly.
56 # - Added some exception calls and/or more informative error messages in some
57 # places they were missing.
58 # - Fixed up (some of) the ugly code formatting, e.g. changed mixture of
59 # leading tabs / space to be consistently spaces and changed indentation
60 # levels to always be 4 spaces.
61 #
62 # Also see specific embedded comments tagged with DJA for more details
63 #
64
65 # POD
66
67 =head1 NAME
68
69 TFBS::DB::JASPAR - interface to MySQL relational database of pattern matrices. Currently status: experimental.
70
71
72 =head1 SYNOPSIS
73
74 =over 4
75
76 =item * creating a database object by connecting to the existing JASPAR6-type database
77
78 my $db = TFBS::DB::JASPAR6->connect("dbi:mysql:JASPAR6:myhost",
79 "myusername",
80 "mypassword");
81
82 =item * retrieving a TFBS::Matrix::* object from the database
83
84 # retrieving a PFM by ID
85 my $pfm = $db->get_Matrix_by_ID('M0079','PFM');
86
87 #retrieving a PWM by name
88 my $pwm = $db->get_Matrix_by_name('NF-kappaB', 'PWM');
89
90 =item * retrieving a set of matrices as a TFBS::MatrixSet object according to various criteria
91
92 # retrieving a set of PWMs from a list of IDs:
93 my @IDlist = ('M0019', 'M0045', 'M0073', 'M0101');
94 my $matrixset = $db->get_MatrixSet(-IDs => \@IDlist,
95 -matrixtype => "PWM");
96
97 # retrieving a set of ICMs from a list of names:
98 @namelist = ('p50', 'p53', 'HNF-1'. 'GATA-1', 'GATA-2', 'GATA-3');
99 my $matrixset = $db->get_MatrixSet(-names => \@namelist,
100 -matrixtype => "ICM");
101
102
103
104 =item * creating a new JASPAR6-type database named MYJASPAR6:
105
106 my $db = TFBS::DB::JASPAR4->create("dbi:mysql:MYJASPAR6:myhost",
107 "myusername",
108 "mypassword");
109
110 =item * storing a matrix in the database (currently only PFMs):
111
112 #let $pfm is a TFBS::Matrix::PFM object
113 $db->store_Matrix($pfm);
114
115
116
117 =back
118
119 =head1 DESCRIPTION
120
121 TFBS::DB::JASPAR is a read/write database interface module that
122 retrieves and stores TFBS::Matrix::* and TFBS::MatrixSet
123 objects in a relational database. The interface is nearly identical
124 to the JASPAR2 and JASPAR4 interface, while the underlying data model is different
125
126
127 =head1 JASPAR6 DATA MODEL
128
129 JASPAR6 is working name for a relational database model used
130 for storing transcriptional factor pattern matrices in a MySQL database.
131 It was initially designed (JASPAR2) to store matrices for the JASPAR database of
132 high quality eukaryotic transcription factor specificity profiles by
133 Albin Sandelin and Wyeth W. Wasserman. Besides the profile matrix itself,
134 this data model stores profile ID (unique), name, structural class,
135 basic taxonomic and bibliographic information
136 as well as some additional, and custom, tags.
137
138 Here goes a moore thorough description on tables and IDs
139
140
141
142
143 ----------------------- ADVANCED ---------------------------------
144
145 For the developers and the curious, here is the JASPAR6 data model:
146
147
148
149 MISSING TEXT HEER ON HOW IT WORKS
150
151
152 It is our best intention to hide the details of this data model, which we
153 are using on a daily basis in our work, from most TFBS users.
154 Most users should only know the methods to store the data and
155 which tags are supported.
156
157 -------------------------------------------------------------------------
158
159
160 =head1 FEEDBACK
161
162 Please send bug reports and other comments to the author.
163
164 =head1 AUTHOR - Boris Lenhard
165
166 Boris Lenhard E<lt>[email protected]<gt>
167
168 =head1 APPENDIX
169
170 The rest of the documentation details each of the object
171 methods. Internal methods are preceded with an underscore.
172
173 =cut
174
175 # The code begins HERE:
176
177 package TFBS::DB::JASPAR7;
178 use vars qw(@ISA $AUTOLOAD);
179
180 # we need all three matrices due to the redundancy in JASPAR2 data model
181 # which will hopefully be removed in JASPAR3
182
183 use TFBS::Matrix::PWM;
184 use TFBS::Matrix::PFM;
185 use TFBS::Matrix::ICM;
186 use TFBS::TFFM;
187
188 use TFBS::MatrixSet;
189 use Bio::Root::Root;
190 use DBI;
191 # use TFBS::DB; # eventually
192 use strict;
193
194 @ISA = qw(TFBS::DB Bio::Root::Root);
195
196 #########################################################################
197 # CONSTANTS
198 #########################################################################
199
200 use constant DEFAULT_CONNECTSTRING => "dbi:mysql:JASPAR_DEMO"; # on localhost
201 use constant DEFAULT_USER => "";
202 use constant DEFAULT_PASSWORD => "";
203
204 #########################################################################
205 # PUBLIC METHODS
206 #########################################################################
207
208 =head2 new
209
210 Title : new
211 Usage : DEPRECATED - for backward compatibility only
212 Use connect() or create() instead
213
214 =cut
215
216 sub new {
217 _new(@_);
218 }
219
220 =head2 connect
221
222 Title : connect
223 Usage : my $db =
224 TFBS::DB::JASPAR6->connect("dbi:mysql:DATABASENAME:HOSTNAME",
225 "USERNAME",
226 "PASSWORD");
227 Function: connects to the existing JASPAR6-type database and
228 returns a database object that interfaces the database
229 Returns : a TFBS::DB::JASPAR6 object
230 Args : a standard database connection triplet
231 ("dbi:mysql:DATABASENAME:HOSTNAME", "USERNAME", "PASSWORD")
232 In place of DATABASENAME, HOSTNAME, USERNAME and PASSWORD,
233 use the actual values. PASSWORD and USERNAME might be
•234 optional, depending on the user's access permissions for
235 the database server.
236
237 =cut
238
239 sub connect { #DONE
240 # a more intuitive syntax for the constructor
241 my ($caller, @connection_args) = @_;
242 $caller->new(-connect => \@connection_args);
243 }
244
245 =head2 dbh
246
247 Title : dbh
248 Usage : my $dbh = $db->dbh();
249 $dbh->do("UPDATE matrix_data SET name='ADD1' WHERE NAME='SREBP2'");
250 Function: returns the DBI database handle of the MySQL database
251 interfaced by $db; THIS IS USED FOR WRITING NEW METHODS
252 FOR DIRECT RELATIONAL DATABASE MANIPULATION - if you
253 have write access AND do not know what you are doing,
254 you can severely corrupt the data
255 For documentation about database handle methods, see L<DBI>
256 Returns : the database (DBI) handle of the MySQL JASPAR2-type
257 relational database associated with the TFBS::DB::JASPAR2
258 object
259 Args : none
260
261 =cut
262
263 sub dbh { #DONE
264 my ($self, $dbh) = @_;
265 $self->{'dbh'} = $dbh if $dbh;
266 return $self->{'dbh'};
267 }
268
269 =head2 store_Matrix
270
271 Title : store_Matrix
272 Usage : $db->store_Matrix($matrixobject);
273 Function: Stores the contents of a TFBS::Matrix::DB object in the database
274 Returns : 0 on success; $@ contents on failure
275 (this is too C-like and may change in future versions)
276 Args : (PFM_object)
277 A TFBS::Matrix::PFM, FBS::Matrix::PWM or FBS::Matrix::ICM object.
278 PFM object are recommended to use, as they are eaily converted to
279 other formats
280 # might have to give version and collection here
281 Comment : this is an experimental method that is not 100% bulletproof;
282 use at your own risk
283
284 =cut
285
286 sub store_Matrix { #PROBABLY DONE
287 # collection, version are taken from the corresponding tags. Warn if they are not there
288 ;
289 my ($self, @PFMs) = @_;
290 my $err;
291 foreach my $pfm (@PFMs) {
292 eval {
293 my $int_id = $self->_store_matrix($pfm)
294 ; # needs to have collection and version
295 $self->_store_matrix_data($pfm, $int_id);
296 $self->_store_matrix_annotation($pfm, $int_id);
297 $self->_store_matrix_species($pfm, $int_id);
298 $self->_store_matrix_acc($pfm, $int_id);
299 };
300 }
301 return $@;
302 }
303
304 sub create { #done
305 my ($caller, $connectstring, $user, $password) = @_;
306 if ( $connectstring
307 and $connectstring =~ /dbi:mysql:(\w+)(.*)/)
308 {
309 # connect to the server;
310 my $dbh = DBI->connect("dbi:mysql:mysql" . $2, $user, $password)
311 or die("Error connecting to the database");
312
313 # create database and open it
314 $dbh->do("create database $1")
315 or die("Error creating database.");
316 $dbh->do("use $1");
317
318 # create tables
319 _create_tables($dbh);
320
321 $dbh->disconnect;
322
323 # run "new" with new database
324
325 return $caller->new(-connect => [$connectstring, $user, $password]);
326 } else {
327 die( "Missing or malformed connect string for "
328 . "TFBS::DB::JASPAR2 connection.");
329 }
330 }
331
332 =head2 get_Matrix_by_ID
333
334 Title : get_Matrix_by_ID
335 Usage : my $pfm = $db->get_Matrix_by_ID('M00034', 'PFM');
336 Function: fetches matrix data under the given ID from the
337 database and returns a TFBS::Matrix::* object
338 Returns : a TFBS::Matrix::* object; the exact type of the
339 object depending on what form the matrix is stored
340 in the database (PFM is default)
341 Args : (Matrix_ID)
342 Matrix_ID id is a string which refers to the stable
343 JASPAR ID (usually something like "MA0001") with
344 or without version numbers. "MA0001" will give the
345 latest version on MA0001, while "MA0001.2" will give
346 the second version, if existing. Warnings will be
347 given for non-existing matrices.
348
349 =cut
350
351 sub get_Matrix_by_ID { #DONE. MAYBE :)
352
353 my ($self, $q, $mt) = @_; # q is a stable ID with possible version number
354
355 # jsp6
356 $mt = (uc($mt) or "PFM");
357 unless (defined $q) {
358 $self->throw("No ID passed to get_Matrix_by_ID");
359 }
360
361 my $ucmt = uc $mt;
362 # separate stable ID and version number
363 my ($base_ID, $version) = split(/\./, $q);
364 $version = $self->_get_latest_version($base_ID)
365 unless $version; # latest version per default
366
367 # get internal ID - also a check for validity
368 my $int_id = $self->_get_internal_id($base_ID, $version);
369
370 # get matrix using internal ID
371
372 my $m = $self->_get_Matrix_by_int_id($int_id, $ucmt);
373 #warn ref($m);
374
375 return ($m);
376 }
377
378 =head2 get_Matrix_by_name
379
380 Title : get_Matrix_by_name
381 Usage : my $pfm = $db->get_Matrix_by_name('HNF-1');
382 Function: fetches matrix data under the given name from the
383 database and returns a TFBS::Matrix::* object
384 Returns : a TFBS::Matrix::* object; the exact type of the object
385 depending on what form the matrix object was stored in
386 the database (default PFM))
387 Args : (Matrix_name)
388
389 Warning : According to the current JASPAR6 data model, name is
390 not necessarily a unique identifier. Also, names change
391 over time.
392 In the case where
393 there are several matrices with the same name in the
394 database, the function fetches the first one and prints
395 a warning on STDERR. You've been warned.
396 Some matrices have multiple versions. The function will
397 return the latest version. For specific versions, use
398 get_Matrix_by_ID($ID.$version)
399
400 =cut
401
402 sub get_Matrix_by_name { #DONE
403 my ($self, $name, $mt) = @_;
404 unless (defined $name) {
405 $self->throw("No name passed to get_Matrix_by_name.");
406 }
407 # sanity check: are there many different stable IDs with same name?
408
409 my $sth = $self->dbh->prepare(
410 qq!SELECT distinct BASE_ID FROM MATRIX
411 WHERE NAME="$name"!
412 );
413 $sth->execute();
414 my (@stable_ids) = $sth->fetchrow_array();
415 my $L = scalar @stable_ids;
416 $self->warn("There are $L distinct stable IDs with name '$name'")
417 if scalar $L > 1;
418
419 return $self->get_Matrix_by_ID($stable_ids[0], $mt);
420 }
421
422 =head2 get_MatrixSet
423
424 Title : get_MatrixSet
425 Usage : my $matrixset = $db->get_MatrixSet(%args);
426 Function: fetches matrix data under for all matrices in the database
427 matching criteria defined by the named arguments
428 and returns a TFBS::MatrixSet object
429 Returns : a TFBS::MatrixSet object
430 Args : This method accepts named arguments, corresponding to arbitrary tags, and also some utility functions
431 Note that this is different from JASPAR2 and to some extent JASPAR4. As any tag is supported for
432 database storage, any tag can be used for information retrieval.
433 Additionally, arguments as 'name','class','collection' can be used (even though
434 they are not tags.
435 Per default, only the last version of the matrix is given. The only way to get older matrices out of this
436 to use an array of IDs with actual versions like MA0001.1, or set the argyment -all_versions=>1, in which case you get all versions for each stable ID
437
438
439
440
441 Examples include:
442 Fundamental matrix features
443 -all # gives absolutely all matrix entry, regardless of versin and collection. Only useful for backup situations and sanity checks. Takes precedence over everything else
444
445 -ID # a reference to an array of stable IDs (strings), with or without version, as above. tyically something like "MA0001.2" . Takes precedence over everything salve -all
446 -name # a reference to an array of
447 # transcription factor names (string). Will only take latest version. NOT a preferred way to access since names change over time
448 -collection # a string corresponding to a JASPAR collection. Per default CORE
449 -all_versions # gives all matrix versions that fit with rest of criteria, including obsolete ones.Is off per default.
450 # Typical usage is in combiation with a stable IDs withou versions to get all versinos of a particular matrix
451 Typical tag queries:
452 These can be either a string or a reference to an array of strings. If it is an arrau it will be interpreted as as an "or"s statement
453 -class # a reference to an array of
454 # structural class names (strings)
455 -species # a reference to an array of
456 # NCBI Taxonomy IDs (integers)
457 -taxgroup # a reference to an array of
458 # higher taxonomic categories (string)
459
460 Computed features of the matrices
461 -min_ic # float, minimum total information content
462 # of the matrix.
463 -matrixtype #string describing type of matrix to retrieve. If left out, the format
464 will revert to the database format, which is PFM.
465
466 The arguments that expect list references are used in database
467 query formulation: elements within lists are combined with 'OR'
468 operators, and the lists of different types with 'AND'. For example,
469
470 my $matrixset = $db->(-class => ['TRP_CLUSTER', 'FORKHEAD'],
471 -species => ['Homo sapiens', 'Mus musculus'],
472 );
473
474 gives a set of TFBS::Matrix::PFM objects (given that the matrix models are stored as such)
475 whose (structural clas is 'TRP_CLUSTER' OR'FORKHEAD') AND (the species they are derived
476 from is 'Homo sapiens'OR 'Mus musculus').
477
478 As above, unless IDs with version numbers are used, only one matrix per stable ID wil be returned: the matrix with the highest version number
479
480 The -min_ic filter is applied after the query in the sense that the
481 matrices profiles with total information content less than specified
482 are not included in the set.
483
484
485
486 =cut
487
488 # jsp6
489 sub get_MatrixSet
490 { # IC conetent and matrix stuff is not there yet, rest should work
491 my ($self, %args) = @_;
492
493 #jsp6
494 $args{'-collection'} = 'CORE' unless $args{'-collection'};
495
496 $args{'-all_versions'} = 0 unless $args{'-all_versions'};
497
498 my @IDlist = @{$self->_get_IDlist_by_query(%args)}
499 ; # the IDlist here are INTERNAL ids
500
501 my $type;
502 my $matrixset = TFBS::MatrixSet->new();
503
504 foreach my $int_id (@IDlist) {
505
506 my $matrix = $self->_get_Matrix_by_int_id($int_id);
507
508 if (defined $args{'-min_ic'}) {
509 # we assume the matrix IS a PFM, o something in normal space at
510 # least unless it explicitly says otherwise in tag=matrixtype
511 # if so warn and do not use IC content
512 # this is not foolproof in any way
513
514 #
515 # Fixed up logic to actually check $matrix->isa(TFBS::Matrix::ICM)
516 # before checking the matrixtype tag. Also check that matrixtype
517 # tag is defined before comparison to prevent annoying "Use of
518 # uninitialized value in string eq" messages from perl.
519 # DJA 2012/05/11
520 #
521 if ($matrix->isa("TFBS::Matrix::ICM")
522 || (defined $matrix->{tags}{matrixtype}
523 && $matrix->{tags}{matrixtype} eq "ICM")
524 )
525 {
526 next if ($matrix->total_ic() < $args{'-min_ic'});
527 } elsif ($matrix->isa("TFBS::Matrix::PFM")) {
528 next if ($matrix->to_ICM->total_ic() < $args{'-min_ic'});
529 } else {
530 warn
531 "Warning: you are assessing information content on matrices that are not in PFM or ICM format. Skipping this criteria";
532 next;
533 }
534
535 }
536
537 # length
538 if (defined $args{'-length'}) {
539 next if ($matrix->length() < $args{'-length'});
540 }
541
542 # number of sites within
543 # since column sums MIGHT be slightly different we take the integer of the mean of the columns
544 # or really int( sum of matrix/#columns)
545 if (defined $args{'-sites'}) {
546 my $sum = 0;
547 foreach (1 .. $matrix->length) {
548 $sum += $matrix->column_sum();
549 }
550 $sum = int($sum / $matrix->length);
551 #warn $matrix->ID, " $sum is $sum";
552 next if ($sum < $args{'-sites'});
553 }
554
555 #ugly code: think about this a bit.
556
557 if ($args{'-matrixtype'} && $matrix->isa("TFBS::Matrix::PFM")) {
558 if ($args{'-matrixtype'} eq ('PWM')) {
559
560 $matrix = $matrix->to_PWM();
561 }
562 if ($args{'-matrixtype'} eq ('ICM')) {
563
564 $matrix = $matrix->to_PWM();
565 }
566 }
567
568 $matrixset->add_Matrix($matrix);
569 }
570 return $matrixset;
571 }
572
573 sub store_MatrixSet
574 { #DONE a wrapper around store_Matrix (which also can take an array of matrices, so utility only
575 my ($self, $matrixset) = @_;
576 my $it = $matrixset->Iterator();
577 while (my $matrix_object = $it->next) {
578 # do whatever you want with individual matrix objects
579 $self->store_Matrix(
580 $matrix_object);
581 }
582
583 }
584
585 =head2 delete_Matrix_having_ID
586
587 Title : delete_Matrix_having_ID
588 Usage : $db->delete_Matrix_with_ID('M00045.1');
589 Function: Deletes the matrix having the given ID from the database
590 Returns : 0 on success; $@ contents on failure
591 (this is too C-ike and may change in future versions)
592 Args : (ID)
593 A string. Has to be a matrix ID with version suffix in JASPAR6.
594 Comment : Yeah, yeah, 'delete_Matrix_having_ID' is a stupid name
595 for a method, but at least it should be obviuos what it does.
596
597 =cut
598
599 sub delete_Matrix_having_ID {
600 my ($self, @IDs) = @_;
601 # this has to be versioned IDs
602 foreach my $ID (@IDs) {
603 my ($base_id, $version) = split(/\./, $ID);
604 unless ($version) {
605 warn
606 "You have supplied a non-versioned matrix ID to delete. Skipping $ID ";
607 return 0;
608 }
609 # get relevant internal ID
610 my ($int_id) = $self->_get_internal_id($base_id, $version);
611
612 eval {
613 my $q_ID = $self->dbh->quote($int_id);
614 foreach my $table (
615 qw (MATRIX_DATA
616 MATRIX
617 MATRIX_SPECIES
618 MATRIX_PROTEIN
619 MATRIX_ANNOTATION)
620 ) {
621 $self->dbh->do("DELETE from $table where ID=$q_ID");
622 }
623 };
624 }
625
626 return $@;
627 }
628
629 =head2 get_TFFM_by_ID
630
631 Title : get_TFFM_by_ID
632 Usage : my $tffm = $db->get_TFFM_by_ID('TFFM0001');
633 Function: fetches TFFM data under the given ID from the
634 database and returns a TFBS::TFFM object.
635 Returns : a TFBS::TFFM object
636 Args : TFFM ID
637 TFFM_ID id is a string which refers to the stable
638 JASPAR TFFM ID (usually something like "TFFM0001") with
639 or without version numbers. "TFFM0001" will give the
640 latest version on TFFM0001, while "TFFM0001.2" will give
641 the second version, if existing. Warnings will be
642 given for non-existing TFFMs.
643
644 =cut
645
646 sub get_TFFM_by_ID {
647
648 my ($self, $id) = @_; # id is a stable ID with possible version number
649
650 unless (defined $id) {
651 $self->throw("No ID passed to get_TFFM_by_ID");
652 }
653
654 # separate stable ID and version number
655 my ($base_ID, $version) = split(/\./, $id);
656
657 # latest version per default
658 $version = $self->_get_TFFM_latest_version($base_ID) unless $version;
659
660 # get internal ID - also a check for validity
661 my $int_id = $self->_get_TFFM_internal_id($base_ID, $version);
662
663 # get TFFM using internal ID
664 my $tffm = $self->_get_TFFM_by_int_id($int_id);
665
666 return ($tffm);
667 }
668
669 =head2 get_TFFM_by_matrix_ID
670
671 Title : get_TFFM_by_matrix_ID
672 Usage : my $tffm = $db->get_TFFM_by_matrix_ID('MA0001.1');
673 Function: fetches TFFM data under related to the given matrix ID from the
674 database and returns a TFBS::TFFM object.
675 Returns : a TFBS::TFFM object
676 Args : Matrix ID
677 Matrix ID id is a string which refers to the stable
678 JASPAR matrix ID (usually something like "MA0148.3").
679 Note that this *should* be a fully qualified matrix ID (with
680 version) as the TFFM is related to a specific version of a
681 matrix. If no matrix version is given, the latest version of
682 the matrix is retrieved and the corresponding TFFM for that
683 matrix version is retrieved (could be no TFFM).
684 In general only a few matrices have associated TFFMs so in many
685 cases no TFFM will be retrieved. In these cases we return undef.
686
687 =cut
688
689 sub get_TFFM_by_matrix_ID {
690
691 # id is a fully qualified matrix stable ID including version number
692 my ($self, $matrix_id) = @_;
693
694 unless (defined $matrix_id) {
695 $self->throw("No matrix ID passed to get_TFFM_by_matrix_ID");
696 }
697
698 # separate matrix stable ID and version number
699 my ($matrix_base_id, $matrix_version) = split(/\./, $matrix_id);
700
701 # latest matrix version per default
702 $matrix_version = $self->_get_latest_version($matrix_base_id)
703 unless $matrix_version;
704
705 my $sth = $self->dbh->prepare(
706 qq! SELECT BASE_ID, VERSION, NAME, LOG_P_1ST_ORDER, LOG_P_DETAILED,
707 EXPERIMENT_NAME FROM TFFM WHERE MATRIX_BASE_ID = "$matrix_base_id"
708 AND MATRIX_VERSION = "$matrix_version" !
709 );
710
711 $sth->execute();
712
713 my ($base_id, $version, $name, $log_p_1st_order, $log_p_detailed,
714 $exp_name) = $sth->fetchrow_array();
715
716 my $tffm;
717 if ($base_id) {
718 eval {
719 $tffm = TFBS::TFFM->new(
720 -ID => "$base_id.$version",
721 -name => $name,
722 -log_p_1st_order => $log_p_1st_order,
723 -log_p_detailed => $log_p_detailed,
724 -experiment_name => $exp_name,
725
726 #
727 # OR we could retrieve the matrix and set the corresponding
728 # attribute
729 #
730 -matrix_ID => "$matrix_base_id.$matrix_version"
731 )
732 };
733
734 if ($@) {
735 $self->throw($@);
736 }
737
738 #
739 # Instead of storing the matrix ID, get the related matrix and store in
740 # the matrix attribute.
741 #
742 # my $matrix = $self->get_Matrix_by_ID(
743 # "$matrix_base_id.$matrix_version", 'PFM'
744 # );
745 #
746 # $tffm->matrix($matrix);
747 #
748 } else {
749 warn "No TFFM exists for matrix '$matrix_base_id.$matrix_version'";
750 }
751
752 return $tffm;
753 }
754
755 =head2 get_TFFM_by_name
756
757 Title : get_TFFM_by_name
758 Usage : my $tffm = $db->get_TFFM_by_name('HNF-1');
759 Function: fetches TFFM data under the given name from the
760 database and returns a TFBS::TFFM object
761 Returns : a TFBS::TFFM object
762 Args : A TFFM name - the name of the transcription factor for which
763 this TFFM was modelled. This is the same as the name of the
764 matrix used to train the TFFM.
765
766 Warning : According to the current JASPAR data model, name is
767 not necessarily a unique identifier. Also, names change
768 over time.
769 In the case where there are several TFFMs with the same name in
770 the database, the function fetches the first one and prints
771 a warning on STDERR. You've been warned.
772 Some matrices have multiple versions. The function will
773 return the latest version. For specific versions, use
774 get_TFFM_by_ID($ID.$version)
775
776 =cut
777
778 sub get_TFFM_by_name {
779 my ($self, $name) = @_;
780
781 unless (defined $name) {
782 $self->throw("No name passed to get_TFFM_by_name.");
783 }
784
785 # sanity check: are there many different stable IDs with same name?
786 my $sth = $self->dbh->prepare(
787 qq!SELECT distinct BASE_ID FROM TFFM WHERE NAME="$name"!
788 );
789 $sth->execute();
790
791 my (@stable_ids) = $sth->fetchrow_array();
792 my $L = scalar @stable_ids;
793
794 $self->warn("There are $L distinct stable IDs with name '$name'")
795 if scalar $L > 1;
796
797 return $self->get_TFFM_by_ID($stable_ids[0]);
798 }
799
800 #########################################################################
801 # PRIVATE METHODS
802 #########################################################################
803
804 sub _new { #PROBABLY OK
805 my ($caller, %args) = @_;
806 my $class = ref $caller || $caller;
807 my $self = bless {}, $class;
808
809 my ($connectstring, $user, $password);
810
811 if ($args{'-connect'} and (ref($args{'-connect'}) eq "ARRAY")) {
812 ($connectstring, $user, $password) = @{$args{'-connect'}};
813 } elsif ($args{'-create'} and (ref($args{'-create'}) eq "ARRAY")) {
814 return $caller->create(@{-args {'create'}});
815 } else {
816 ($connectstring, $user, $password) =
817 (DEFAULT_CONNECTSTRING, DEFAULT_USER, DEFAULT_PASSWORD);
818 }
819
820 $self->dbh(DBI->connect($connectstring, $user, $password, {mysql_enable_utf8 => 1}));
821
822 return $self;
823 }
824
825 sub _store_matrix_data { # DONE
826 my ($self, $pfm, $int_id, $ACTION) = @_;
827 my @base = qw(A C G T);
828 my $matrix = $pfm->matrix();
829 my $type;
830 my $sth =
831 $self->dbh->prepare(q! INSERT INTO MATRIX_DATA VALUES(?,?,?,?) !);
832
833 for my $i (0 .. 3) {
834 for my $j (0 .. ($pfm->length - 1)) {
835 $sth->execute(
836 $int_id,
837
838 $base[$i],
839 $j + 1,
840 $matrix->[$i][$j]
841 ) or $self->throw("Error executing query.");
842 }
843 }
844
845 }
846
847 sub _store_matrix { #DONE
848 # creation of the matrix will also give an internal unique ID
849 # (incremental int) which will be returned to use for the other tables
850 my ($self, $pfm, $ACTION) = @_;
851
852 #
853 # Added check that the version is not already stored as part of the ID.
854 # Also added a more informative insertion exception message.
855 # DJA 2016/08/26
856 #
857
858 my $id = $pfm->ID;
859
860 my $base_id;
861 my $version;
862 if ($id =~ /^(\S+)\.(\d+)/) {
863 $base_id = $1;
864 $version = $2;
865 } else {
866 $base_id = $id;
867 }
868
869 unless ($version) {
870 # Get collection and version from the matrix tags
871 $version = $pfm->{'tags'}{'version'};
872 }
873
874 # will warn but not die if version is missing: will assume 1
875 unless ($version) {
876 warn "WARNING: Lacking version number for "
877 . $pfm->ID
878 . ". Setting version=1";
879 $version = 1;
880 }
881
882 my $collection = $pfm->{'tags'}{'collection'};
883 unless ($collection) {
884 warn "WARNING: Lacking collection name for "
885 . $pfm->ID
886 . ". Setting collection to an empty string. You probably do not want this";
887 $collection = '';
888 }
889
890 # sanity check: do we already have this cobination of base ID and version?
891 # If we do, die
892 my $sth = $self->dbh->prepare(
893 qq! select count(*) from MATRIX where VERSION=$version
894 and BASE_ID= "$base_id" and collection="$collection" !
895 );
896 $sth->execute;
897 my ($sanity_count) = $sth->fetchrow_array;
898
899 if ($sanity_count > 0) {
900 warn
901 "WARNING: Database input inconsistency: You have already have $sanity_count $base_id matrices of version $version in collection $collection. Terminating program";
902 die;
903 }
904
905 # insert data
906
907 $sth = $self->dbh->prepare(
908 q! INSERT INTO MATRIX
909 VALUES(?,?,?,?,?) !
910 );
911
912 # update next sth with actual version and collection: DO
913 $sth->execute(0, $collection, $pfm->ID, $version, $pfm->name)
914 or $self->throw(
915 sprintf("Error inserting matrix %s as %s.%d to %s collection",
916 $pfm->name, $pfm->ID, $version, $collection)
917 );
918
919 # get the actual (new) iternal ID
920
921 my $int_id = $self->dbh->{q{mysql_insertid}};
922
923 return $int_id;
924 }
925
926 sub _store_matrix_annotation { # DONE
927 #
928 # this is for tag-value items that are not one-to-many (so, not species
929 # and not acc)
930
931 #
932 # We do need to store multiple values of class and family. In the case
933 # of profiles representing dimers, the TFs making up the dimer may have
934 # different TF classes and families. It also seemed abitrary to have a
935 # primary key constraint on the ID + TAG. This has been removed.
936 #
937 # Added more informative messages to insertion failure exceptions.
938 # Modified split to also handle spaces around comma.
939 # DJA 2015/08/26
940 #
941
942 my ($self, $pfm, $int_id, $ACTION) = @_;
943 my $sth = $self->dbh->prepare(
944 q! INSERT INTO MATRIX_ANNOTATION
945 (ID, tag, val)
946 VALUES(?,?,?) !
947 );
948
949 # get all tags
950 # but skip out collection or version as we already have those in the
951 # MATRIX table
952
953 # special handling for class which mighht have a true slot
954
955 my %tags = $pfm->all_tags();
956 if (defined($pfm->{class})) {
957 $tags{class} = $pfm->{class};
958 }
959
960 foreach my $tag (keys %tags) {
961 next if $tag eq "collection";
962 next if $tag eq "version";
963 next if $tag eq "species";
964
965 #
966 # The 'acc' tag was commented out in JASPAR6. Not sure the reasoning
967 # as this stores the protein accession (UniProt IDs) which are
968 # stored in the MATRIX_PROTEIN table and therefore should NOT be
969 # stored in the MATRIX_ANNOTATION table and therefore *should* be
970 # skipped here.
971 # DJA 2015/08/26
972 #
973 next if $tag eq "acc";
974
975 # next if $tag eq "class";
976 #$sth->execute($int_id, $tag, ($tags{$tag} or ""),)
977 # or $self->throw("Error executing query");
978 #
979 # Since we may have multiple values stored in some tags we need to
980 # handle this. Assume that they may be stored either as array
981 # references or as strings with comma separators.
982 # DJA 2015/08/26
983 #
984 my $vals = $tags{$tag};
985 if (ref $vals eq 'ARRAY') {
986 foreach my $val (@$vals) {
987 $val =~ s/^\s+//;
988 $val =~ s/\s+$//;
989 $sth->execute($int_id, $tag, $val) or $self->throw(
990 "Error inserting tag/value pair ('$tag', '$val')"
991 . " into MATRIX_ANNOTATION"
992 );
993 }
994 } else {
995 foreach my $val (split(/\s*\,\s*/, $vals)) {
996 $val =~ s/^\s+//;
997 $val =~ s/\s+$//;
998 $sth->execute($int_id, $tag, $val) or $self->throw(
999 "Error inserting tag/value pair ('$tag', '$val')"
1000 . " into MATRIX_ANNOTATION"
1001 );
1002 }
1003 }
1004 }
1005 }
1006
1007 sub _store_matrix_species { # DONE
1008 #these are for species IDs - can be several
1009 # these are taken from the tag "species"
1010 # if that tag is a reference to an array we walk over the array
1011 # if it is a comma-separated string we split the string
1012
1013 #
1014 # Added exception handling/messages for insertion failure.
1015 # Modified split to also handle spaces around comma.
1016 # DJA 2015/08/26
1017 #
1018
1019 my ($self, $pfm, $int_id, $ACTION) = @_;
1020 my $sth = $self->dbh->prepare(
1021 q! INSERT INTO MATRIX_SPECIES
1022 VALUES(?,?) !
1023 );
1024
1025 #sanity check: are there any species? Its ok not to have it.
1026 return () unless $pfm->{'tags'}{'species'};
1027 #is the species a string or an arrayref?
1028 if (ref($pfm->{'tags'}{'species'}) eq 'ARRAY') {
1029 # walkthru array
1030 foreach my $species (@{$pfm->{'tags'}{'species'}}) {
1031 $sth->execute($int_id, $species) or $self->throw(
1032 "Error inserting species '$species' for matrix $int_id)"
1033 );
1034 }
1035 } else {
1036 # split and walk thru
1037 foreach my $species (split(/\s*\,\s*/, $pfm->{'tags'}{'species'})) {
1038 $species =~ s/^\s+//;
1039 $sth->execute($int_id, $species) or $self->throw(
1040 "Error inserting species '$species' for matrix $int_id)"
1041 );
1042 }
1043 }
1044 }
1045
1046 sub _store_matrix_acc { # DONE
1047 #these are for protein accession numbers - can be several
1048 # these are taken from the tag "acc"
1049 # if that tag is a reference to an array we walk over the array
1050 # if it is a comma-separated string we split the string
1051
1052 #
1053 # For some reason the MATRIX_PROTEIN table had a primary key constraint
1054 # on the matrix ID field, preventing multiple proteins from being stored
1055 # here. That was presumably an oversight or otherwise an out of date table
1056 # definition.
1057 #
1058 # Also added more informative insertion exception messages.
1059 # DJA 2016/08/26
1060 #
1061
1062 my ($self, $pfm, $int_id, $ACTION) = @_;
1063 my $sth = $self->dbh->prepare(
1064 q! INSERT INTO MATRIX_PROTEIN
1065 VALUES(?,?) !
1066 );
1067
1068 #sanity check: are there any accession numbers? Its ok not to have it.
1069 return () unless $pfm->{'tags'}{'acc'};
1070
1071 #is the protein ID a string or an arrayref?
1072 if (ref($pfm->{'tags'}{'acc'}) eq 'ARRAY') {
1073 # walkthru array
1074 foreach my $acc (@{$pfm->{'tags'}{'acc'}}) {
1075 $acc =~ s/\s//g;
1076 $sth->execute($int_id, $acc) or $self->throw(
1077 "Error inserting protein '$acc' for matrix $int_id)"
1078 );
1079 }
1080 } else {
1081 # split and walk thru
1082 foreach my $acc (split(/\,/, $pfm->{'tags'}{'acc'})) {
1083 $acc =~ s/\s//g;
1084 $sth->execute($int_id, $acc) or $self->throw(
1085 "Error inserting protein '$acc' for matrix $int_id)"
1086 );
1087 }
1088
1089 }
1090 }
1091
1092 #when creating: try to support arbitrary tags
1093
1094 sub _create_tables { # DONE
1095 # utility function
1096
1097 # If you want to change the databse schema,
1098 # this is the right place to do it
1099
1100 #
1101 # Changed the primary key constraint on MATRIX_ANNOTATION to a simple
1102 # key. There are tags for which we do want to have multiple entries, e.g.
1103 # in the case of a dimer profiles the two TFs making up the dimer may
1104 # have a different TF class and/or family therefore we need to store more
1105 # than one record with tag 'class' or tag 'family' for the same matrix
1106 # ID.
1107 #
1108 # Also added key on ID to MATRIX_PROTEIN and MATRIX_SPECIES which seemed
1109 # to be missing.
1110 #
1111 # We may also want to set the charset/collation to utf8/utf8_unicode_ci
1112 # either at the DB level or to the individual table definitions
1113 # (particularly for the MATRIX_ANNOTATION table) to handle non-Latin
1114 # characters correctly.
1115 #
1116 # DJA 2015/08/26
1117 #
1118
1119 my $dbh = shift;
1120 my @queries = (
1121 q!
1122 CREATE TABLE MATRIX (
1123 ID INT(11) NOT NULL AUTO_INCREMENT,
1124 COLLECTION VARCHAR (16) DEFAULT '',
1125 BASE_ID VARCHAR (16) DEFAULT '' NOT NULL ,
1126 VERSION TINYINT(4) DEFAULT 1 NOT NULL ,
1127 NAME VARCHAR (255) DEFAULT '' NOT NULL,
1128 PRIMARY KEY (ID))
1129 !,
1130
1131 q!
1132 CREATE TABLE MATRIX_DATA (
1133 ID INT(11) NOT NULL,
1134 row VARCHAR(1) NOT NULL,
1135 col TINYINT(3) UNSIGNED NOT NULL,
1136 val float(10,3),
1137 PRIMARY KEY (ID, row, col))
1138 !,
1139
1140 q!
1141 CREATE TABLE MATRIX_ANNOTATION (
1142 ID INT(11) NOT NULL,
1143 TAG VARCHAR(255) DEFAULT '' NOT NULL,
1144 VAL varchar(255) DEFAULT '',
1145 KEY (ID, TAG))
1146 !,
1147
1148 q!
1149 CREATE TABLE MATRIX_SPECIES (
1150 ID INT(11) NOT NULL,
1151 TAX_ID VARCHAR(255) DEFAULT '' NOT NULL
1152 KEY (ID))
1153 !,
1154
1155 q!
1156 CREATE TABLE MATRIX_PROTEIN (
1157 ID INT(11) NOT NULL,
1158 ACC VARCHAR(255) DEFAULT '' NOT NULL
1159 KEY (ID))
1160 !,
1161
1162 q!
1163 CREATE TABLE TFFM (
1164 ID int(11) NOT NULL auto_increment,
1165 BASE_ID varchar(16) NOT NULL,
1166 VERSION tinyint(4) NOT NULL,
1167 MATRIX_BASE_ID varchar(16) NOT NULL,
1168 MATRIX_VERSION tinyint(4) NOT NULL,
1169 NAME varchar(255) NOT NULL,
1170 LOG_P_1ST_ORDER float default NULL,
1171 LOG_P_DETAILED float default NULL,
1172 EXPERIMENT_NAME varchar(255) default NULL,
1173 PRIMARY KEY (ID),
1174 KEY BASE_ID (BASE_ID, VERSION),
1175 KEY MATRIX_BASE_ID (MATRIX_BASE_ID, MATRIX_VERSION)
1176 !
1177 );
1178
1179 foreach my $query (@queries) {
1180 $dbh->do($query)
1181 or die("Error executing the query: $query\n");
1182 }
1183 }
1184
1185 sub _get_matrixstring { #DONE
1186 my ($self, $ID) = @_;
1187 #my %dbname = (PWM => 'pwm', PFM => 'raw', ICM => 'info');
1188 #unless (defined $dbname{$mt}) {
1189 #$self->throw("Unsupported matrix type: ".$mt);
1190 #}
1191 my $sth;
1192 my $qID = $self->dbh->quote($ID);
1193 my $matrixstring = "";
1194 foreach my $base (qw(A C G T)) {
1195 $sth = $self->dbh->prepare(
1196 "SELECT val FROM MATRIX_DATA
1197 WHERE ID=$qID AND row='$base' ORDER BY col"
1198 );
1199 $sth->execute;
1200 $matrixstring
1201 .= join(" ", (map {$_->[0]} @{$sth->fetchall_arrayref()})) . "\n";
1202 }
1203 $sth->finish;
1204 return undef if $matrixstring eq "\n" x 4;
1205
1206 return $matrixstring;
1207 }
1208
1209 sub _get_latest_version { #DONE
1210 my ($self, $base_ID) = @_;
1211 # SELECT VERSION FROM MATRIX WHERE BASE_ID=? ORDER BY VERSION DESC LIMIT 1
1212 my $sth = $self->dbh->prepare(
1213 qq!SELECT VERSION FROM MATRIX
1214 WHERE BASE_ID="$base_ID"
1215 ORDER BY VERSION DESC LIMIT 1!
1216 );
1217 $sth->execute;
1218 my ($latest) = $sth->fetchrow_array();
1219
1220 return ($latest);
1221 }
1222
1223 sub _get_internal_id { #DONE
1224 # picks out the internal id for a a stable id+ version. Also checks if this cobo exists or not
1225 my ($self, $base_ID, $version) = @_;
1226 # SELECT ID FROM MATRIX WHERE BASE_ID=? and VERSION=?
1227 my $sth = $self->dbh->prepare(
1228 qq!SELECT ID FROM MATRIX
1229 WHERE BASE_ID="$base_ID" AND VERSION="$version"!
1230 );
1231 $sth->execute;
1232 my ($int_id) = $sth->fetchrow_array();
1233
1234 return ($int_id);
1235 }
1236
1237 sub _get_Matrix_by_int_id { #done
1238 my ($self, $int_id, $mt) = @_;
1239
1240 my $matrixobj;
1241 $mt = 'PFM' unless $mt;
1242 # get the matrix as a string
1243 my $matrixstring = $self->_get_matrixstring($int_id) || return undef;
1244
1245 #get remaining data in the matrix table: name, collection
1246 my $sth = $self->dbh->prepare(
1247 qq!SELECT BASE_ID,VERSION, COLLECTION,NAME FROM MATRIX
1248 WHERE ID="$int_id"!
1249 );
1250 $sth->execute();
1251 my ($base_ID, $version, $collection, $name) = $sth->fetchrow_array();
1252
1253 # jsp6
1254 # get species
1255 ##$sth=$self->dbh->prepare(qq!SELECT TAX_ID FROM MATRIX_SPECIES WHERE ID="$int_id"!);
1256 $sth = $self->dbh->prepare(
1257 qq!SELECT GROUP_CONCAT(TAX_ID SEPARATOR ', ') as TAX_ID FROM MATRIX_SPECIES WHERE ID="$int_id"!
1258 );
1259 $sth->execute();
1260 my @tax_ids;
1261 while (my ($res) = $sth->fetchrow_array()) {
1262 my @res_v = split(/,/, $res);
1263 my @res_v2 = grep(s/^\s*(.*)\s*$/\1/g, @res_v);
1264 push(@tax_ids, @res_v2);
1265 }
1266
1267 # jsp6
1268 # get acc
1269 ##$sth=$self->dbh->prepare(qq!SELECT ACC FROM MATRIX_PROTEIN WHERE ID="$int_id"!);
1270 $sth = $self->dbh->prepare(
1271 qq!SELECT GROUP_CONCAT(ACC SEPARATOR ', ') as ACC FROM MATRIX_PROTEIN WHERE ID="$int_id"!
1272 );
1273 $sth->execute();
1274 my @accs;
1275 while (my ($res) = $sth->fetchrow_array()) {
1276 my @res_v = split(/,/, $res);
1277 my @res_v2 = grep(s/^\s*(.*)\s*$/\1/g, @res_v);
1278 push(@accs, @res_v2);
1279 }
1280
1281 # jsp6
1282 # get remaining annotation as tags, form ANNOTATION table
1283 my %tags;
1284 $sth = $self->dbh->prepare(
1285 qq{SELECT TAG, VAL FROM MATRIX_ANNOTATION WHERE ID = "$int_id" });
1286 $sth->execute();
1287
1288 ## my @key_to_split=("acc", "medline", "pazar_tf_id"); #if acc in MATRIX_ANNOTATION
1289 #my @key_to_split=("medline", "pazar_tf_id");
1290 #
1291 # Added 'class' and 'family' to keys to split. Since we have dimers that
1292 # may have different classes / families. Previously stored in DB as comma
1293 # separated lists, now store as separate records.
1294 # XXX But this breaks the interface code! FIXME XXX
1295 # DJA 2015/09/10
1296 #
1297 #my @key_to_split = ("medline", "pazar_tf_id", "tfbs_shape_id", "tfe_id", "class", "family");
1298 my @key_to_split = ("class", "family", "medline", "pazar_tf_id", "tfbs_shape_id", "tfe_id");
1299
1300 #
1301 # See FIXME comment below.
1302 # DJA 2015/09/14
1303 #
1304 #foreach my $key (@key_to_split) {
1305 # $tags{$key} = ['-'];
1306 #}
1307
1308 #
1309 # Fixed so that we can have multiple comma separated values, values in
1310 # separate rows of the table or a combination thereof. We really should
1311 # try to get away from having to specify which keys can be split (should
1312 # be handled more gracefully).
1313 # DJA 2015/09/14
1314 #
1315 my $vals;
1316 while (my ($tag, $val) = $sth->fetchrow_array()) {
1317 $vals = [];
1318 if ($tag ~~ @key_to_split) {
1319 my @val_v = split(/,/, $val);
1320 my @val_v2 = grep(s/^\s*(.*)\s*$/\1/g, @val_v);
1321 #push(@$vals, @val_v2);
1322 #$tags{$tag} = $vals;
1323 push @{$tags{$tag}}, @val_v2;
1324 } else {
1325 $tags{$tag} = $val;
1326 }
1327 }
1328
1329 #
1330 # XXX FIXME
1331 # This really doesn't belong here. It is done for the purposes of the web
1332 # interface but this is DB code which should not presume how the returned
1333 # data is going to be used. That should be handled in the JASPAR web code
1334 # modules. JASPAR web code currently expects all keys to split to exist!
1335 # DJA 2015/09/14
1336 # XXX FIXME
1337 #
1338 foreach my $key (@key_to_split) {
1339 $tags{$key} = ['-'] unless $tags{$key};
1340 }
1341
1342 # jsp6
1343 $tags{'collection'} = $collection;
1344 $tags{'species'} = \@tax_ids; # as array reference instead of strigifying
1345 $tags{'acc'} = \@accs; # same, if acc MATRIX_PROTEIN
1346
1347 #
1348 my $class = $tags{'class'};
1349 delete($tags{'class'});
1350 #
1351 eval(
1352 "\$matrixobj = TFBS::Matrix::PFM->new" . '
1353 ( -ID => "$base_ID.$version",
1354 -name => $name,
1355 -class => $class,
1356 -tags => \%tags,
1357 -matrixstring => $matrixstring # FIXME - temporary
1358 );'
1359 );
1360 if ($@) {
1361 $self->throw($@);
1362 }
1363 # warn $int_id, "\t", ref($matrixobj);
1364 return ($matrixobj->to_PWM) if $mt eq "PWM";
1365 return ($matrixobj->to_ICM) if $mt eq "ICM";
1366 return ($matrixobj); # default PFM
1367 }
1368
1369 ##jsp6
1370 sub _get_IDlist_by_query { #needs cleanup. NOT for the faint-hearted.
1371 my ($self, %args) = @_;
1372
1373 warn '_get_IDlist_by_query | $self || ', $self;
1374 warn '_get_IDlist_by_query | %args || ', %args;
1375
1376 # called by get_MatrixSet
1377 # warn $args{"-collection"};
1378
1379 $args{'-collection'} = 'CORE' unless $args{'-collection'};
1380
1381 # returns a set of internal IDs with whicj to get the actual matrices
1382 # current idea:
1383 # 1: first catch non-tag things like collection, name and version, species
1384 # makw one query for these if they are named and check the IDs for "latest" unless requested not to.
1385 # these are AND statements
1386 # 2:then do the rest on tag level:
1387 # to be able to do this with actual and tattemnet innthe tag table, we do an inner join query, which is kept separate just for convenice
1388 # we then intersect 1 and 2
1389 # 3: then do matrix-based features such as ic, with, number of sites etc, for the surviving matrices. This shold happen in the get_matrixset part
1390
1391 my @int_ids_to_return;
1392
1393 ## jsp6 - autosearch
1394 if ($args{'-auto'}) {
1395 ##my $sth=$self->dbh->prepare (qq!SELECT ID FROM MATRIX WHERE BASE_ID=?!);
1396 my $sth = $self->dbh->prepare(
1397 qq!SELECT U.ID FROM (SELECT ID, BASE_ID as VAL FROM MATRIX UNION ALL SELECT ID, NAME as VAL FROM MATRIX UNION ALL SELECT ID, ACC as VAL FROM MATRIX_PROTEIN UNION ALL SELECT ID, TAX_ID as VAL FROM MATRIX_SPECIES UNION ALL SELECT ID, SPECIES as VAL FROM MATRIX_SPECIES,TAX WHERE MATRIX_SPECIES.TAX_ID=TAX.TAX_ID UNION ALL SELECT ID, NAME as VAL FROM MATRIX_SPECIES,TAX_EXT WHERE MATRIX_SPECIES.TAX_ID=TAX_EXT.TAX_ID AND MATRIX_SPECIES.TAX_ID=9606 UNION ALL SELECT ID, VAL as VAL FROM MATRIX_ANNOTATION) AS U WHERE LOWER(`VAL`) LIKE LOWER(?)!
1398 );
1399
1400 warn '_get_IDlist_by_query | $sth || ', $sth;
1401
1402 foreach my $stID (@{$args{'-auto'}}) {
1403 warn '_get_IDlist_by_query | $stID || ', $stID;
1404 my ($stable_ID, $version) = split(/\./, $stID)
1405 ; # ignore vesion here, this is a stupidity filter
1406 #$sth->execute($stable_ID);
1407 $sth->execute("%" . $stable_ID . "%");
1408 while (my ($int_id) = $sth->fetchrow_array()) {
1409 warn '_get_IDlist_by_query | $int_id || ', $int_id;
1410 push(@int_ids_to_return, $int_id);
1411 }
1412 }
1413 return \@int_ids_to_return;
1414 }
1415
1416 # should redo so that matrix_annotation queries are separate, with an intersect in the end
1417 #special case 1: get ALL matrices. Higher priority than all
1418
1419 if ($args{'-all'}) {
1420 my $sth = $self->dbh->prepare(qq!SELECT ID FROM MATRIX!);
1421 $sth->execute();
1422 my @a;
1423 while (my ($i) = $sth->fetchrow_array()) {
1424 push(@a, $i);
1425 }
1426 return \@a;
1427 }
1428
1429 # ids: special case2 which is has higher priority than any other except the above (ignore all others
1430 if ($args{'-ID'}) {
1431 # these might be either stable IDs or stableid.version.
1432 # if just stable ID and if all_versions==1, take all versions, otherwise the latest
1433 if ($args{-all_versions}) {
1434 my $sth = $self->dbh->prepare(
1435 qq!SELECT ID FROM MATRIX WHERE BASE_ID=?!);
1436 foreach my $stID (@{$args{'-ID'}}) {
1437 my ($stable_ID, $version) = split(/\./, $stID)
1438 ; # ignore vesion here, this is a stupidity filter
1439 $sth->execute($stable_ID);
1440 while (my ($int_id) = $sth->fetchrow_array()) {
1441 push(@int_ids_to_return, $int_id);
1442 }
1443 }
1444 } else { # only the lastest version, or the requested version
1445 foreach my $stID (@{$args{'-ID'}}) {
1446 #warn $stID;
1447 my ($stable_ID, $version) = split(/\./, $stID);
1448 $version = $self->_get_latest_version($stable_ID)
1449 unless $version;
1450 my $int_id = $self->_get_internal_id($stable_ID, $version);
1451 push(@int_ids_to_return, $int_id) if $int_id;
1452 }
1453 }
1454 return \@int_ids_to_return;
1455 }
1456
1457 my @tables = ("MATRIX M");
1458 my @and;
1459
1460 # in matrix table: collection,
1461 if ($args{-collection}) {
1462 my $q = ' (COLLECTION=';
1463 if (ref $args{-collection} eq "ARRAY") { # so, possibly several
1464 my @a;
1465 foreach (@{$args{-collection}}) {
1466 push(@a, "\"$_\"");
1467 }
1468 $q .= join(" or COLLECTION=", @a);
1469 } else { # just one - typical usage
1470 $q .= "\"$args{-collection}\"";
1471 }
1472 $q .= " ) ";
1473 push(@and, $q);
1474 }
1475
1476 # in matrix table: names. Is something that is basically only used from the web interface
1477 # typically used by the get_matrix_by_name function instead
1478
1479 if ($args{-name}) {
1480 my $q = ' (NAME=';
1481 if (ref $args{-name} eq "ARRAY") { # so, possibly several
1482 my @a;
1483 foreach (@{$args{-name}}) {
1484 push(@a, "\"$_\"");
1485 }
1486 $q .= join(" or NAME=", @a);
1487 } else { # just one - typical usage
1488 $q .= "\"$args{-name}\"";
1489 }
1490 $q .= " ) ";
1491 push(@and, $q);
1492 }
1493
1494 # in species table: tax.id: possibly many species with OR in between
1495 if ($args{-species}) {
1496 push(@tables, "MATRIX_SPECIES S");
1497 my $q = " M.ID=S.ID and (TAX_ID= ";
1498 if (ref $args{-species} eq "ARRAY") { # so, possibly several
1499 my @a;
1500 foreach (@{$args{-species}}) {
1501 push(@a, "\"$_\"");
1502 }
1503 $q .= join(" or TAX_ID=", @a);
1504 } else { # just one - typical usage
1505 $q .= "=\"$args{-species}\"";
1506 }
1507 $q .= ") ";
1508 push(@and, $q);
1509 }
1510
1511 # TAG_BASED
1512 # an internal join query:should be able to handle up to 26 tags-value combos with ANDS in between
1513 # Very ugly code ahead:
1514
1515 my (@inner_tables, @internal_ands1, @internal_ands2);
1516 my $int_counter = 0; # for keeping track of names;
1517 my @alpha = ("a" .. "z");
1518
1519 my %arrayref;
1520 foreach my $key (keys %args) {
1521 next if $key eq "-min_ic";
1522 next if $key eq "-matrixtype";
1523 next if $key eq "-species";
1524 next if $key eq "-collection";
1525 next if $key eq "-all_versions";
1526 next if $key eq "-all";
1527 next if $key eq "-ID";
1528 next if $key eq "-length";
1529 next if $key eq "-name";
1530 my $oldkey = $key;
1531 $key =~ s/-//;
1532 $arrayref{$key} = $args{$oldkey};
1533 }
1534 if (%arrayref) {
1535 # get an internal name for the table
1536 push(@internal_ands2, " M.ID=a.ID ");
1537 my @a;
1538 foreach my $key (keys %arrayref) {
1539 my $tname = $alpha[$int_counter];
1540 push(@inner_tables, "MATRIX_ANNOTATION $tname");
1541 push(@internal_ands1,
1542 $alpha[$int_counter] . ".ID="
1543 . $alpha[$int_counter - 1] . ".ID")
1544 unless $int_counter == 0;
1545 $int_counter++;
1546 # is the thing aupplied an array reference in inteslf: make an "or" query from that
1547 if (ref $arrayref{$key} eq "ARRAY") {
1548 my @b;
1549 foreach (@{$arrayref{$key}}) {
1550 push(@b, $self->dbh->quote($_));
1551 }
1552 my $orstring = join(" or $tname.VAL=", @b);
1553 push(@a, "($tname.TAG=\"$key\" AND ($tname.VAL=$orstring))");
1554 }
1555 #or not
1556 else {
1557 push(@a,
1558 "($tname.TAG=\"$key\" AND $tname.VAL=\"$arrayref{$key}\")"
1559 );
1560 }
1561 }
1562 my $s = " ( " . join(" AND ", @a) . ")";
1563 push(@internal_ands2, $s);
1564 }
1565
1566 my $qq =
1567 "SELECT distinct(M.ID) from "
1568 . join(",", (@tables, @inner_tables))
1569 . " where"
1570 . join(" AND ", (@and, @internal_ands1, @internal_ands2));
1571
1572 # warn $qq;
1573
1574 #do actual mammoth query,and check for latest matrix
1575 my $sth = $self->dbh->prepare($qq);
1576 $sth->execute();
1577 my @r;
1578
1579 while (my ($int_id) = $sth->fetchrow_array) {
1580 if ($args{-all_versions}) {
1581 push(@r, $int_id);
1582 } else {
1583 # is latest?
1584 push(@r, $int_id) if ($self->_is_latest_version($int_id) == 1);
1585 }
1586 }
1587 warn "Warning: Zero matrices returned with current critera"
1588 unless scalar @r;
1589 return \@r;
1590
1591 }
1592 ## jsp6 - checkpoint
1593
1594 sub _is_latest_version {
1595 # is a particular internal ID representingthe latest matrix (collapse on base ids)
1596 my ($self, $int_id) = @_;
1597 my $sth = $self->dbh->prepare(
1598 qq! select count(*) from MATRIX
1599 where BASE_ID= (SELECT BASE_ID from MATRIX where ID=$int_id)
1600 AND VERSION>(SELECT VERSION from MATRIX where ID=$int_id) !
1601 );
1602 $sth->execute();
1603 my ($count) = $sth->fetchrow_array();
1604 return (1)
1605 if $count == 0; # no matrices with higher version ID and same base id
1606 return (0);
1607 }
1608
1609 sub _get_TFFM_latest_version {
1610 my ($self, $base_ID) = @_;
1611
1612 # SELECT VERSION FROM TFFM WHERE BASE_ID=? ORDER BY VERSION DESC LIMIT 1
1613 my $sth = $self->dbh->prepare(
1614 qq!SELECT VERSION FROM TFFM
1615 WHERE BASE_ID="$base_ID"
1616 ORDER BY VERSION DESC LIMIT 1!
1617 );
1618 $sth->execute;
1619
1620 my ($latest) = $sth->fetchrow_array();
1621
1622 return ($latest);
1623 }
1624
1625 sub _get_TFFM_internal_id {
1626 # picks out the internal id for a stable id version. Also checks if this
1627 # combo exists or not
1628 my ($self, $base_ID, $version) = @_;
1629
1630 # SELECT ID FROM TFFM WHERE BASE_ID=? and VERSION=?
1631 my $sth = $self->dbh->prepare(
1632 qq!SELECT ID FROM TFFM
1633 WHERE BASE_ID="$base_ID" AND VERSION="$version"!
1634 );
1635 $sth->execute;
1636
1637 my ($int_id) = $sth->fetchrow_array();
1638
1639 return ($int_id);
1640 }
1641
1642 sub _get_TFFM_by_int_id { #done
1643 my ($self, $int_id) = @_;
1644
1645 my $tffm;
1646
1647 my $sth = $self->dbh->prepare(
1648 qq! SELECT BASE_ID, VERSION, MATRIX_BASE_ID, MATRIX_VERSION, NAME,
1649 LOG_P_1ST_ORDER, LOG_P_DETAILED, EXPERIMENT_NAME FROM TFFM
1650 WHERE ID = "$int_id" !
1651 );
1652
1653 $sth->execute();
1654
1655 my ($base_id, $version, $matrix_base_id, $matrix_version, $name,
1656 $log_p_1st_order, $log_p_detailed, $exp_name) = $sth->fetchrow_array();
1657
1658 my $tffm;
1659 eval {
1660 $tffm = TFBS::TFFM->new(
1661 -ID => "$base_id.$version",
1662 -name => $name,
1663 -log_p_1st_order => $log_p_1st_order,
1664 -log_p_detailed => $log_p_detailed,
1665 -experiment_name => $exp_name,
1666
1667 #
1668 # OR we could retrieve the matrix and set the corresponding
1669 # attribute
1670 #
1671 -matrix_ID => "$matrix_base_id.$matrix_version"
1672 )
1673 };
1674
1675 if ($@) {
1676 $self->throw($@);
1677 }
1678
1679 #
1680 # Instead of storing the matrix ID, get the related matrix and store in
1681 # the matrix attribute.
1682 #
1683 # my $matrix = $self->get_Matrix_by_ID(
1684 # "$matrix_base_id.$matrix_version", 'PFM'
1685 # );
1686 #
1687 # $tffm->matrix($matrix);
1688 #
1689
1690 return $tffm; # default PFM
1691 }
1692
1693 sub _is_TFFM_latest_version {
1694 my ($self, $int_id) = @_;
1695
1696 my $sth = $self->dbh->prepare(
1697 qq! select count(*) from TFFM
1698 where BASE_ID = (SELECT BASE_ID from TFFM where ID = $int_id)
1699 AND VERSION > (SELECT VERSION from TFFM where ID = $int_id) !
1700 );
1701
1702 $sth->execute();
1703
1704 my ($count) = $sth->fetchrow_array();
1705
1706 # no TFFMs with higher version ID and same base id
1707 return (1) if $count == 0;
1708
1709 return (0);
1710 }
1711
1712 sub DESTROY {
1713 #OK
1714 $_[0]->dbh->disconnect() if $_[0]->dbh;
1715 }